Search in sources :

Example 1 with RelationType

use of com.facebook.presto.sql.analyzer.RelationType in project presto by prestodb.

the class LogicalPlanner method createInsertPlan.

private RelationPlan createInsertPlan(Analysis analysis, Insert insertStatement) {
    Analysis.Insert insert = analysis.getInsert().get();
    TableMetadata tableMetadata = metadata.getTableMetadata(session, insert.getTarget());
    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, insertStatement.getQuery());
    Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, insert.getTarget());
    Assignments.Builder assignments = Assignments.builder();
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        if (column.isHidden()) {
            continue;
        }
        Symbol output = symbolAllocator.newSymbol(column.getName(), column.getType());
        int index = insert.getColumns().indexOf(columns.get(column.getName()));
        if (index < 0) {
            assignments.put(output, new NullLiteral());
        } else {
            Symbol input = plan.getSymbol(index);
            Type tableType = column.getType();
            Type queryType = symbolAllocator.getTypes().get(input);
            if (queryType.equals(tableType) || metadata.getTypeManager().isTypeOnlyCoercion(queryType, tableType)) {
                assignments.put(output, input.toSymbolReference());
            } else {
                Expression cast = new Cast(input.toSymbolReference(), tableType.getTypeSignature().toString());
                assignments.put(output, cast);
            }
        }
    }
    ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build());
    List<Field> fields = visibleTableColumns.stream().map(column -> Field.newUnqualified(column.getName(), column.getType())).collect(toImmutableList());
    Scope scope = Scope.builder().withRelationType(new RelationType(fields)).build();
    plan = new RelationPlan(projectNode, scope, projectNode.getOutputSymbols());
    Optional<NewTableLayout> newTableLayout = metadata.getInsertLayout(session, insert.getTarget());
    return createTableWriterPlan(analysis, plan, new InsertReference(insert.getTarget()), visibleTableColumnNames, newTableLayout);
}
Also used : QualifiedObjectName(com.facebook.presto.metadata.QualifiedObjectName) TableMetadata(com.facebook.presto.metadata.TableMetadata) ExplainAnalyzeNode(com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode) NOT_FOUND(com.facebook.presto.spi.StandardErrorCode.NOT_FOUND) Field(com.facebook.presto.sql.analyzer.Field) TableWriterNode(com.facebook.presto.sql.planner.plan.TableWriterNode) ValuesNode(com.facebook.presto.sql.planner.plan.ValuesNode) BIGINT(com.facebook.presto.spi.type.BigintType.BIGINT) Delete(com.facebook.presto.sql.tree.Delete) Map(java.util.Map) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) Assignments(com.facebook.presto.sql.planner.plan.Assignments) OutputNode(com.facebook.presto.sql.planner.plan.OutputNode) ImmutableSet(com.google.common.collect.ImmutableSet) Query(com.facebook.presto.sql.tree.Query) Explain(com.facebook.presto.sql.tree.Explain) String.format(java.lang.String.format) SqlParser(com.facebook.presto.sql.parser.SqlParser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) NullLiteral(com.facebook.presto.sql.tree.NullLiteral) List(java.util.List) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) NOT_SUPPORTED(com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) ConnectorId(com.facebook.presto.connector.ConnectorId) LimitNode(com.facebook.presto.sql.planner.plan.LimitNode) PlanOptimizer(com.facebook.presto.sql.planner.optimizations.PlanOptimizer) LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) NewTableLayout(com.facebook.presto.metadata.NewTableLayout) WriterTarget(com.facebook.presto.sql.planner.plan.TableWriterNode.WriterTarget) PrestoException(com.facebook.presto.spi.PrestoException) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Type(com.facebook.presto.spi.type.Type) PlanNode(com.facebook.presto.sql.planner.plan.PlanNode) Objects.requireNonNull(java.util.Objects.requireNonNull) Cast(com.facebook.presto.sql.tree.Cast) VARBINARY(com.facebook.presto.spi.type.VarbinaryType.VARBINARY) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) PlanSanityChecker(com.facebook.presto.sql.planner.sanity.PlanSanityChecker) CreateTableAsSelect(com.facebook.presto.sql.tree.CreateTableAsSelect) Session(com.facebook.presto.Session) InsertReference(com.facebook.presto.sql.planner.plan.TableWriterNode.InsertReference) RelationType(com.facebook.presto.sql.analyzer.RelationType) DeleteNode(com.facebook.presto.sql.planner.plan.DeleteNode) Insert(com.facebook.presto.sql.tree.Insert) Scope(com.facebook.presto.sql.analyzer.Scope) ProjectNode(com.facebook.presto.sql.planner.plan.ProjectNode) Expression(com.facebook.presto.sql.tree.Expression) ColumnHandle(com.facebook.presto.spi.ColumnHandle) CreateName(com.facebook.presto.sql.planner.plan.TableWriterNode.CreateName) IdentityLinkedHashMap(com.facebook.presto.util.maps.IdentityLinkedHashMap) TableFinishNode(com.facebook.presto.sql.planner.plan.TableFinishNode) Metadata(com.facebook.presto.metadata.Metadata) Statement(com.facebook.presto.sql.tree.Statement) Cast(com.facebook.presto.sql.tree.Cast) ColumnMetadata(com.facebook.presto.spi.ColumnMetadata) NewTableLayout(com.facebook.presto.metadata.NewTableLayout) Assignments(com.facebook.presto.sql.planner.plan.Assignments) InsertReference(com.facebook.presto.sql.planner.plan.TableWriterNode.InsertReference) Field(com.facebook.presto.sql.analyzer.Field) RelationType(com.facebook.presto.sql.analyzer.RelationType) TableMetadata(com.facebook.presto.metadata.TableMetadata) ConnectorTableMetadata(com.facebook.presto.spi.ConnectorTableMetadata) ColumnHandle(com.facebook.presto.spi.ColumnHandle) Type(com.facebook.presto.spi.type.Type) RelationType(com.facebook.presto.sql.analyzer.RelationType) Scope(com.facebook.presto.sql.analyzer.Scope) Expression(com.facebook.presto.sql.tree.Expression) Analysis(com.facebook.presto.sql.analyzer.Analysis) ProjectNode(com.facebook.presto.sql.planner.plan.ProjectNode) NullLiteral(com.facebook.presto.sql.tree.NullLiteral)

Example 2 with RelationType

use of com.facebook.presto.sql.analyzer.RelationType in project presto by prestodb.

the class RelationPlanner method addCoercions.

private RelationPlan addCoercions(RelationPlan plan, Type[] targetColumnTypes) {
    List<Symbol> oldSymbols = plan.getFieldMappings();
    RelationType oldDescriptor = plan.getDescriptor().withOnlyVisibleFields();
    verify(targetColumnTypes.length == oldSymbols.size());
    ImmutableList.Builder<Symbol> newSymbols = new ImmutableList.Builder<>();
    Field[] newFields = new Field[targetColumnTypes.length];
    Assignments.Builder assignments = Assignments.builder();
    for (int i = 0; i < targetColumnTypes.length; i++) {
        Symbol inputSymbol = oldSymbols.get(i);
        Type inputType = symbolAllocator.getTypes().get(inputSymbol);
        Type outputType = targetColumnTypes[i];
        if (outputType != inputType && !metadata.getTypeManager().isTypeOnlyCoercion(inputType, outputType)) {
            Expression cast = new Cast(inputSymbol.toSymbolReference(), outputType.getTypeSignature().toString());
            Symbol outputSymbol = symbolAllocator.newSymbol(cast, outputType);
            assignments.put(outputSymbol, cast);
            newSymbols.add(outputSymbol);
        } else {
            SymbolReference symbolReference = inputSymbol.toSymbolReference();
            Symbol outputSymbol = symbolAllocator.newSymbol(symbolReference, outputType);
            assignments.put(outputSymbol, symbolReference);
            newSymbols.add(outputSymbol);
        }
        Field oldField = oldDescriptor.getFieldByIndex(i);
        newFields[i] = new Field(oldField.getRelationAlias(), oldField.getName(), targetColumnTypes[i], oldField.isHidden(), oldField.getOriginTable(), oldField.isAliased());
    }
    ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build());
    return new RelationPlan(projectNode, Scope.builder().withRelationType(new RelationType(newFields)).build(), newSymbols.build());
}
Also used : Cast(com.facebook.presto.sql.tree.Cast) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) SymbolReference(com.facebook.presto.sql.tree.SymbolReference) Assignments(com.facebook.presto.sql.planner.plan.Assignments) Field(com.facebook.presto.sql.analyzer.Field) ComparisonExpressionType(com.facebook.presto.sql.tree.ComparisonExpressionType) ArrayType(com.facebook.presto.type.ArrayType) MapType(com.facebook.presto.type.MapType) Type(com.facebook.presto.spi.type.Type) RelationType(com.facebook.presto.sql.analyzer.RelationType) ExpressionInterpreter.evaluateConstantExpression(com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) RelationType(com.facebook.presto.sql.analyzer.RelationType) ProjectNode(com.facebook.presto.sql.planner.plan.ProjectNode)

Example 3 with RelationType

use of com.facebook.presto.sql.analyzer.RelationType in project presto by prestodb.

the class RelationPlanner method planCrossJoinUnnest.

private RelationPlan planCrossJoinUnnest(RelationPlan leftPlan, Join joinNode, Unnest node) {
    RelationType unnestOutputDescriptor = analysis.getOutputDescriptor(node);
    // Create symbols for the result of unnesting
    ImmutableList.Builder<Symbol> unnestedSymbolsBuilder = ImmutableList.builder();
    for (Field field : unnestOutputDescriptor.getVisibleFields()) {
        Symbol symbol = symbolAllocator.newSymbol(field);
        unnestedSymbolsBuilder.add(symbol);
    }
    ImmutableList<Symbol> unnestedSymbols = unnestedSymbolsBuilder.build();
    // Add a projection for all the unnest arguments
    PlanBuilder planBuilder = initializePlanBuilder(leftPlan);
    planBuilder = planBuilder.appendProjections(node.getExpressions(), symbolAllocator, idAllocator);
    TranslationMap translations = planBuilder.getTranslations();
    ProjectNode projectNode = (ProjectNode) planBuilder.getRoot();
    ImmutableMap.Builder<Symbol, List<Symbol>> unnestSymbols = ImmutableMap.builder();
    UnmodifiableIterator<Symbol> unnestedSymbolsIterator = unnestedSymbols.iterator();
    for (Expression expression : node.getExpressions()) {
        Type type = analysis.getType(expression);
        Symbol inputSymbol = translations.get(expression);
        if (type instanceof ArrayType) {
            unnestSymbols.put(inputSymbol, ImmutableList.of(unnestedSymbolsIterator.next()));
        } else if (type instanceof MapType) {
            unnestSymbols.put(inputSymbol, ImmutableList.of(unnestedSymbolsIterator.next(), unnestedSymbolsIterator.next()));
        } else {
            throw new IllegalArgumentException("Unsupported type for UNNEST: " + type);
        }
    }
    Optional<Symbol> ordinalitySymbol = node.isWithOrdinality() ? Optional.of(unnestedSymbolsIterator.next()) : Optional.empty();
    checkState(!unnestedSymbolsIterator.hasNext(), "Not all output symbols were matched with input symbols");
    UnnestNode unnestNode = new UnnestNode(idAllocator.getNextId(), projectNode, leftPlan.getFieldMappings(), unnestSymbols.build(), ordinalitySymbol);
    return new RelationPlan(unnestNode, analysis.getScope(joinNode), unnestNode.getOutputSymbols());
}
Also used : ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) ImmutableMap(com.google.common.collect.ImmutableMap) MapType(com.facebook.presto.type.MapType) ArrayType(com.facebook.presto.type.ArrayType) Field(com.facebook.presto.sql.analyzer.Field) ComparisonExpressionType(com.facebook.presto.sql.tree.ComparisonExpressionType) ArrayType(com.facebook.presto.type.ArrayType) MapType(com.facebook.presto.type.MapType) Type(com.facebook.presto.spi.type.Type) RelationType(com.facebook.presto.sql.analyzer.RelationType) ExpressionInterpreter.evaluateConstantExpression(com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) UnnestNode(com.facebook.presto.sql.planner.plan.UnnestNode) RelationType(com.facebook.presto.sql.analyzer.RelationType) ProjectNode(com.facebook.presto.sql.planner.plan.ProjectNode) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList)

Example 4 with RelationType

use of com.facebook.presto.sql.analyzer.RelationType in project presto by prestodb.

the class RelationPlanner method visitJoin.

@Override
protected RelationPlan visitJoin(Join node, Void context) {
    // TODO: translate the RIGHT join into a mirrored LEFT join when we refactor (@martint)
    RelationPlan leftPlan = process(node.getLeft(), context);
    // Convert CROSS JOIN UNNEST to an UnnestNode
    if (node.getRight() instanceof Unnest || (node.getRight() instanceof AliasedRelation && ((AliasedRelation) node.getRight()).getRelation() instanceof Unnest)) {
        Unnest unnest;
        if (node.getRight() instanceof AliasedRelation) {
            unnest = (Unnest) ((AliasedRelation) node.getRight()).getRelation();
        } else {
            unnest = (Unnest) node.getRight();
        }
        if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
            throw notSupportedException(unnest, "UNNEST on other than the right side of CROSS JOIN");
        }
        return planCrossJoinUnnest(leftPlan, node, unnest);
    }
    RelationPlan rightPlan = process(node.getRight(), context);
    PlanBuilder leftPlanBuilder = initializePlanBuilder(leftPlan);
    PlanBuilder rightPlanBuilder = initializePlanBuilder(rightPlan);
    // NOTE: symbols must be in the same order as the outputDescriptor
    List<Symbol> outputSymbols = ImmutableList.<Symbol>builder().addAll(leftPlan.getFieldMappings()).addAll(rightPlan.getFieldMappings()).build();
    ImmutableList.Builder<JoinNode.EquiJoinClause> equiClauses = ImmutableList.builder();
    List<Expression> complexJoinExpressions = new ArrayList<>();
    List<Expression> postInnerJoinConditions = new ArrayList<>();
    if (node.getType() != Join.Type.CROSS && node.getType() != Join.Type.IMPLICIT) {
        Expression criteria = analysis.getJoinCriteria(node);
        RelationType left = analysis.getOutputDescriptor(node.getLeft());
        RelationType right = analysis.getOutputDescriptor(node.getRight());
        List<Expression> leftComparisonExpressions = new ArrayList<>();
        List<Expression> rightComparisonExpressions = new ArrayList<>();
        List<ComparisonExpressionType> joinConditionComparisonTypes = new ArrayList<>();
        for (Expression conjunct : ExpressionUtils.extractConjuncts(criteria)) {
            conjunct = ExpressionUtils.normalize(conjunct);
            if (!isEqualComparisonExpression(conjunct) && node.getType() != INNER) {
                complexJoinExpressions.add(conjunct);
                continue;
            }
            Set<QualifiedName> dependencies = DependencyExtractor.extractNames(conjunct, analysis.getColumnReferences());
            boolean isJoinUsing = node.getCriteria().filter(JoinUsing.class::isInstance).isPresent();
            if (!isJoinUsing && (dependencies.stream().allMatch(left::canResolve) || dependencies.stream().allMatch(right::canResolve))) {
                // If the conjunct can be evaluated entirely with the inputs on either side of the join, add
                // it to the list complex expressions and let the optimizers figure out how to push it down later.
                // Due to legacy reasons, the expression for "join using" looks like "x = x", which (incorrectly)
                // appears to fit the condition we're after. So we skip them.
                complexJoinExpressions.add(conjunct);
            } else if (conjunct instanceof ComparisonExpression) {
                Expression firstExpression = ((ComparisonExpression) conjunct).getLeft();
                Expression secondExpression = ((ComparisonExpression) conjunct).getRight();
                ComparisonExpressionType comparisonType = ((ComparisonExpression) conjunct).getType();
                Set<QualifiedName> firstDependencies = DependencyExtractor.extractNames(firstExpression, analysis.getColumnReferences());
                Set<QualifiedName> secondDependencies = DependencyExtractor.extractNames(secondExpression, analysis.getColumnReferences());
                if (firstDependencies.stream().allMatch(left::canResolve) && secondDependencies.stream().allMatch(right::canResolve)) {
                    leftComparisonExpressions.add(firstExpression);
                    rightComparisonExpressions.add(secondExpression);
                    joinConditionComparisonTypes.add(comparisonType);
                } else if (firstDependencies.stream().allMatch(right::canResolve) && secondDependencies.stream().allMatch(left::canResolve)) {
                    leftComparisonExpressions.add(secondExpression);
                    rightComparisonExpressions.add(firstExpression);
                    joinConditionComparisonTypes.add(comparisonType.flip());
                } else {
                    // the case when we mix symbols from both left and right join side on either side of condition.
                    complexJoinExpressions.add(conjunct);
                }
            } else {
                complexJoinExpressions.add(conjunct);
            }
        }
        leftPlanBuilder = subqueryPlanner.handleSubqueries(leftPlanBuilder, leftComparisonExpressions, node);
        rightPlanBuilder = subqueryPlanner.handleSubqueries(rightPlanBuilder, rightComparisonExpressions, node);
        // Add projections for join criteria
        leftPlanBuilder = leftPlanBuilder.appendProjections(leftComparisonExpressions, symbolAllocator, idAllocator);
        rightPlanBuilder = rightPlanBuilder.appendProjections(rightComparisonExpressions, symbolAllocator, idAllocator);
        for (int i = 0; i < leftComparisonExpressions.size(); i++) {
            if (joinConditionComparisonTypes.get(i) == ComparisonExpressionType.EQUAL) {
                Symbol leftSymbol = leftPlanBuilder.translate(leftComparisonExpressions.get(i));
                Symbol rightSymbol = rightPlanBuilder.translate(rightComparisonExpressions.get(i));
                equiClauses.add(new JoinNode.EquiJoinClause(leftSymbol, rightSymbol));
            } else {
                Expression leftExpression = leftPlanBuilder.rewrite(leftComparisonExpressions.get(i));
                Expression rightExpression = rightPlanBuilder.rewrite(rightComparisonExpressions.get(i));
                postInnerJoinConditions.add(new ComparisonExpression(joinConditionComparisonTypes.get(i), leftExpression, rightExpression));
            }
        }
    }
    PlanNode root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(node.getType()), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), ImmutableList.<Symbol>builder().addAll(leftPlanBuilder.getRoot().getOutputSymbols()).addAll(rightPlanBuilder.getRoot().getOutputSymbols()).build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());
    if (node.getType() != INNER) {
        for (Expression complexExpression : complexJoinExpressions) {
            Set<InPredicate> inPredicates = subqueryPlanner.collectInPredicateSubqueries(complexExpression, node);
            if (!inPredicates.isEmpty()) {
                InPredicate inPredicate = Iterables.getLast(inPredicates);
                throw notSupportedException(inPredicate, "IN with subquery predicate in join condition");
            }
        }
        // subqueries can be applied only to one side of join - left side is selected in arbitrary way
        leftPlanBuilder = subqueryPlanner.handleUncorrelatedSubqueries(leftPlanBuilder, complexJoinExpressions, node);
    }
    RelationPlan intermediateRootRelationPlan = new RelationPlan(root, analysis.getScope(node), outputSymbols);
    TranslationMap translationMap = new TranslationMap(intermediateRootRelationPlan, analysis, lambdaDeclarationToSymbolMap);
    translationMap.setFieldMappings(outputSymbols);
    translationMap.putExpressionMappingsFrom(leftPlanBuilder.getTranslations());
    translationMap.putExpressionMappingsFrom(rightPlanBuilder.getTranslations());
    if (node.getType() != INNER && !complexJoinExpressions.isEmpty()) {
        Expression joinedFilterCondition = ExpressionUtils.and(complexJoinExpressions);
        joinedFilterCondition = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), joinedFilterCondition);
        Expression rewrittenFilterCondition = translationMap.rewrite(joinedFilterCondition);
        root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(node.getType()), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), ImmutableList.<Symbol>builder().addAll(leftPlanBuilder.getRoot().getOutputSymbols()).addAll(rightPlanBuilder.getRoot().getOutputSymbols()).build(), Optional.of(rewrittenFilterCondition), Optional.empty(), Optional.empty(), Optional.empty());
    }
    if (node.getType() == INNER) {
        // rewrite all the other conditions using output symbols from left + right plan node.
        PlanBuilder rootPlanBuilder = new PlanBuilder(translationMap, root, analysis.getParameters());
        rootPlanBuilder = subqueryPlanner.handleSubqueries(rootPlanBuilder, complexJoinExpressions, node);
        for (Expression expression : complexJoinExpressions) {
            expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), expression);
            postInnerJoinConditions.add(rootPlanBuilder.rewrite(expression));
        }
        root = rootPlanBuilder.getRoot();
        Expression postInnerJoinCriteria;
        if (!postInnerJoinConditions.isEmpty()) {
            postInnerJoinCriteria = ExpressionUtils.and(postInnerJoinConditions);
            root = new FilterNode(idAllocator.getNextId(), root, postInnerJoinCriteria);
        }
    }
    return new RelationPlan(root, analysis.getScope(node), outputSymbols);
}
Also used : Set(java.util.Set) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) FilterNode(com.facebook.presto.sql.planner.plan.FilterNode) ArrayList(java.util.ArrayList) PlanNode(com.facebook.presto.sql.planner.plan.PlanNode) RelationType(com.facebook.presto.sql.analyzer.RelationType) Unnest(com.facebook.presto.sql.tree.Unnest) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) ComparisonExpressionType(com.facebook.presto.sql.tree.ComparisonExpressionType) InPredicate(com.facebook.presto.sql.tree.InPredicate) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) ExpressionInterpreter.evaluateConstantExpression(com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Expression(com.facebook.presto.sql.tree.Expression) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) AliasedRelation(com.facebook.presto.sql.tree.AliasedRelation)

Example 5 with RelationType

use of com.facebook.presto.sql.analyzer.RelationType in project presto by prestodb.

the class RelationPlanner method process.

private SetOperationPlan process(SetOperation node) {
    List<Symbol> outputs = null;
    ImmutableList.Builder<PlanNode> sources = ImmutableList.builder();
    ImmutableListMultimap.Builder<Symbol, Symbol> symbolMapping = ImmutableListMultimap.builder();
    List<RelationPlan> subPlans = node.getRelations().stream().map(relation -> processAndCoerceIfNecessary(relation, null)).collect(toImmutableList());
    for (RelationPlan relationPlan : subPlans) {
        List<Symbol> childOutputSymbols = relationPlan.getFieldMappings();
        if (outputs == null) {
            // Use the first Relation to derive output symbol names
            RelationType descriptor = relationPlan.getDescriptor();
            ImmutableList.Builder<Symbol> outputSymbolBuilder = ImmutableList.builder();
            for (Field field : descriptor.getVisibleFields()) {
                int fieldIndex = descriptor.indexOf(field);
                Symbol symbol = childOutputSymbols.get(fieldIndex);
                outputSymbolBuilder.add(symbolAllocator.newSymbol(symbol.getName(), symbolAllocator.getTypes().get(symbol)));
            }
            outputs = outputSymbolBuilder.build();
        }
        RelationType descriptor = relationPlan.getDescriptor();
        checkArgument(descriptor.getVisibleFieldCount() == outputs.size(), "Expected relation to have %s symbols but has %s symbols", descriptor.getVisibleFieldCount(), outputs.size());
        int fieldId = 0;
        for (Field field : descriptor.getVisibleFields()) {
            int fieldIndex = descriptor.indexOf(field);
            symbolMapping.put(outputs.get(fieldId), childOutputSymbols.get(fieldIndex));
            fieldId++;
        }
        sources.add(relationPlan.getRoot());
    }
    return new SetOperationPlan(sources.build(), symbolMapping.build());
}
Also used : ComparisonExpressionType(com.facebook.presto.sql.tree.ComparisonExpressionType) ExpressionTreeRewriter(com.facebook.presto.sql.tree.ExpressionTreeRewriter) AliasedRelation(com.facebook.presto.sql.tree.AliasedRelation) ListMultimap(com.google.common.collect.ListMultimap) Field(com.facebook.presto.sql.analyzer.Field) Values(com.facebook.presto.sql.tree.Values) ValuesNode(com.facebook.presto.sql.planner.plan.ValuesNode) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Join(com.facebook.presto.sql.tree.Join) JoinUsing(com.facebook.presto.sql.tree.JoinUsing) SetOperation(com.facebook.presto.sql.tree.SetOperation) ExpressionInterpreter.evaluateConstantExpression(com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) Assignments(com.facebook.presto.sql.planner.plan.Assignments) SymbolReference(com.facebook.presto.sql.tree.SymbolReference) Query(com.facebook.presto.sql.tree.Query) QuerySpecification(com.facebook.presto.sql.tree.QuerySpecification) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) ExceptNode(com.facebook.presto.sql.planner.plan.ExceptNode) SampledRelation(com.facebook.presto.sql.tree.SampledRelation) Preconditions.checkState(com.google.common.base.Preconditions.checkState) TupleDomain(com.facebook.presto.spi.predicate.TupleDomain) List(java.util.List) InPredicate(com.facebook.presto.sql.tree.InPredicate) DefaultTraversalVisitor(com.facebook.presto.sql.tree.DefaultTraversalVisitor) SampleNode(com.facebook.presto.sql.planner.plan.SampleNode) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) SemanticExceptions.notSupportedException(com.facebook.presto.sql.analyzer.SemanticExceptions.notSupportedException) Analysis(com.facebook.presto.sql.analyzer.Analysis) LongLiteral(com.facebook.presto.sql.tree.LongLiteral) Optional(java.util.Optional) Except(com.facebook.presto.sql.tree.Except) QualifiedName(com.facebook.presto.sql.tree.QualifiedName) Iterables(com.google.common.collect.Iterables) LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) Table(com.facebook.presto.sql.tree.Table) ArrayType(com.facebook.presto.type.ArrayType) Intersect(com.facebook.presto.sql.tree.Intersect) MapType(com.facebook.presto.type.MapType) ExpressionUtils(com.facebook.presto.sql.ExpressionUtils) ArrayList(java.util.ArrayList) Unnest(com.facebook.presto.sql.tree.Unnest) TableScanNode(com.facebook.presto.sql.planner.plan.TableScanNode) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) Type(com.facebook.presto.spi.type.Type) PlanNode(com.facebook.presto.sql.planner.plan.PlanNode) Objects.requireNonNull(java.util.Objects.requireNonNull) TableSubquery(com.facebook.presto.sql.tree.TableSubquery) Cast(com.facebook.presto.sql.tree.Cast) AggregationNode(com.facebook.presto.sql.planner.plan.AggregationNode) UnnestNode(com.facebook.presto.sql.planner.plan.UnnestNode) Union(com.facebook.presto.sql.tree.Union) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) Iterator(java.util.Iterator) Relation(com.facebook.presto.sql.tree.Relation) Session(com.facebook.presto.Session) RelationType(com.facebook.presto.sql.analyzer.RelationType) ComparisonExpression(com.facebook.presto.sql.tree.ComparisonExpression) Scope(com.facebook.presto.sql.analyzer.Scope) ProjectNode(com.facebook.presto.sql.planner.plan.ProjectNode) UnionNode(com.facebook.presto.sql.planner.plan.UnionNode) Expression(com.facebook.presto.sql.tree.Expression) ColumnHandle(com.facebook.presto.spi.ColumnHandle) TableHandle(com.facebook.presto.metadata.TableHandle) INNER(com.facebook.presto.sql.tree.Join.Type.INNER) CoalesceExpression(com.facebook.presto.sql.tree.CoalesceExpression) FilterNode(com.facebook.presto.sql.planner.plan.FilterNode) IdentityLinkedHashMap(com.facebook.presto.util.maps.IdentityLinkedHashMap) UnmodifiableIterator(com.google.common.collect.UnmodifiableIterator) Row(com.facebook.presto.sql.tree.Row) IntersectNode(com.facebook.presto.sql.planner.plan.IntersectNode) Metadata(com.facebook.presto.metadata.Metadata) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Field(com.facebook.presto.sql.analyzer.Field) PlanNode(com.facebook.presto.sql.planner.plan.PlanNode) RelationType(com.facebook.presto.sql.analyzer.RelationType) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap)

Aggregations

RelationType (com.facebook.presto.sql.analyzer.RelationType)7 ImmutableList (com.google.common.collect.ImmutableList)7 Field (com.facebook.presto.sql.analyzer.Field)6 ImmutableCollectors.toImmutableList (com.facebook.presto.util.ImmutableCollectors.toImmutableList)6 Type (com.facebook.presto.spi.type.Type)5 Expression (com.facebook.presto.sql.tree.Expression)5 ExpressionInterpreter.evaluateConstantExpression (com.facebook.presto.sql.planner.ExpressionInterpreter.evaluateConstantExpression)4 PlanNode (com.facebook.presto.sql.planner.plan.PlanNode)4 ProjectNode (com.facebook.presto.sql.planner.plan.ProjectNode)4 CoalesceExpression (com.facebook.presto.sql.tree.CoalesceExpression)4 ComparisonExpression (com.facebook.presto.sql.tree.ComparisonExpression)4 ComparisonExpressionType (com.facebook.presto.sql.tree.ComparisonExpressionType)4 ArrayList (java.util.ArrayList)4 ColumnHandle (com.facebook.presto.spi.ColumnHandle)3 Scope (com.facebook.presto.sql.analyzer.Scope)3 Assignments (com.facebook.presto.sql.planner.plan.Assignments)3 Session (com.facebook.presto.Session)2 Metadata (com.facebook.presto.metadata.Metadata)2 TableHandle (com.facebook.presto.metadata.TableHandle)2 Analysis (com.facebook.presto.sql.analyzer.Analysis)2