Search in sources :

Example 1 with RelationType

use of io.trino.sql.analyzer.RelationType in project trino by trinodb.

the class LogicalPlanner method getInsertPlan.

private RelationPlan getInsertPlan(Analysis analysis, Table table, Query query, TableHandle tableHandle, List<ColumnHandle> insertColumns, Optional<TableLayout> newTableLayout, Optional<WriterTarget> materializedViewRefreshWriterTarget) {
    TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle);
    Map<NodeRef<LambdaArgumentDeclaration>, Symbol> lambdaDeclarationToSymbolMap = buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator);
    RelationPlanner planner = new RelationPlanner(analysis, symbolAllocator, idAllocator, lambdaDeclarationToSymbolMap, plannerContext, Optional.empty(), session, ImmutableMap.of());
    RelationPlan plan = planner.process(query, null);
    ImmutableList.Builder<Symbol> builder = ImmutableList.builder();
    for (int i = 0; i < plan.getFieldMappings().size(); i++) {
        if (!plan.getDescriptor().getFieldByIndex(i).isHidden()) {
            builder.add(plan.getFieldMappings().get(i));
        }
    }
    List<Symbol> visibleFieldMappings = builder.build();
    Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, tableHandle);
    Assignments.Builder assignments = Assignments.builder();
    boolean supportsMissingColumnsOnInsert = metadata.supportsMissingColumnsOnInsert(session, tableHandle);
    ImmutableList.Builder<ColumnMetadata> insertedColumnsBuilder = ImmutableList.builder();
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        if (column.isHidden()) {
            continue;
        }
        Symbol output = symbolAllocator.newSymbol(column.getName(), column.getType());
        int index = insertColumns.indexOf(columns.get(column.getName()));
        if (index < 0) {
            if (supportsMissingColumnsOnInsert) {
                continue;
            }
            Expression cast = new Cast(new NullLiteral(), toSqlType(column.getType()));
            assignments.put(output, cast);
            insertedColumnsBuilder.add(column);
        } else {
            Symbol input = visibleFieldMappings.get(index);
            Type tableType = column.getType();
            Type queryType = symbolAllocator.getTypes().get(input);
            if (queryType.equals(tableType) || typeCoercion.isTypeOnlyCoercion(queryType, tableType)) {
                assignments.put(output, input.toSymbolReference());
            } else {
                Expression cast = noTruncationCast(input.toSymbolReference(), queryType, tableType);
                assignments.put(output, cast);
            }
            insertedColumnsBuilder.add(column);
        }
    }
    ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build());
    List<ColumnMetadata> insertedColumns = insertedColumnsBuilder.build();
    List<Field> fields = insertedColumns.stream().map(column -> Field.newUnqualified(column.getName(), column.getType())).collect(toImmutableList());
    Scope scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(fields)).build();
    plan = new RelationPlan(projectNode, scope, projectNode.getOutputSymbols(), Optional.empty());
    plan = planner.addRowFilters(table, plan, failIfPredicateIsNotMeet(metadata, session, PERMISSION_DENIED, AccessDeniedException.PREFIX + "Cannot insert row that does not match to a row filter"), node -> {
        Scope accessControlScope = analysis.getAccessControlScope(table);
        // hidden fields are not accessible in insert
        return Scope.builder().like(accessControlScope).withRelationType(accessControlScope.getRelationId(), accessControlScope.getRelationType().withOnlyVisibleFields()).build();
    });
    List<String> insertedTableColumnNames = insertedColumns.stream().map(ColumnMetadata::getName).collect(toImmutableList());
    String catalogName = tableHandle.getCatalogName().getCatalogName();
    TableStatisticsMetadata statisticsMetadata = metadata.getStatisticsCollectionMetadataForWrite(session, catalogName, tableMetadata.getMetadata());
    if (materializedViewRefreshWriterTarget.isPresent()) {
        return createTableWriterPlan(analysis, plan.getRoot(), plan.getFieldMappings(), materializedViewRefreshWriterTarget.get(), insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata);
    }
    InsertReference insertTarget = new InsertReference(tableHandle, insertedTableColumnNames.stream().map(columns::get).collect(toImmutableList()));
    return createTableWriterPlan(analysis, plan.getRoot(), plan.getFieldMappings(), insertTarget, insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata);
}
Also used : Cast(io.trino.sql.tree.Cast) FIXED_HASH_DISTRIBUTION(io.trino.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION) CostProvider(io.trino.cost.CostProvider) TypeSignatureProvider.fromTypes(io.trino.sql.analyzer.TypeSignatureProvider.fromTypes) Delete(io.trino.sql.tree.Delete) InsertReference(io.trino.sql.planner.plan.TableWriterNode.InsertReference) PlanNode(io.trino.sql.planner.plan.PlanNode) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) LongLiteral(io.trino.sql.tree.LongLiteral) Map(java.util.Map) OutputNode(io.trino.sql.planner.plan.OutputNode) TableScanNode(io.trino.sql.planner.plan.TableScanNode) ExplainAnalyzeNode(io.trino.sql.planner.plan.ExplainAnalyzeNode) ExplainAnalyze(io.trino.sql.tree.ExplainAnalyze) Statement(io.trino.sql.tree.Statement) SystemSessionProperties.isCollectPlanStatisticsForAllQueries(io.trino.SystemSessionProperties.isCollectPlanStatisticsForAllQueries) StatisticsWriterNode(io.trino.sql.planner.plan.StatisticsWriterNode) TableExecute(io.trino.sql.tree.TableExecute) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) Set(java.util.Set) PlanSanityChecker(io.trino.sql.planner.sanity.PlanSanityChecker) RelationType(io.trino.sql.analyzer.RelationType) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) CachingStatsProvider(io.trino.cost.CachingStatsProvider) ValuesNode(io.trino.sql.planner.plan.ValuesNode) Session(io.trino.Session) AccessDeniedException(io.trino.spi.security.AccessDeniedException) TableExecuteNode(io.trino.sql.planner.plan.TableExecuteNode) PlanPrinter(io.trino.sql.planner.planprinter.PlanPrinter) QueryPlanner.visibleFields(io.trino.sql.planner.QueryPlanner.visibleFields) CreateReference(io.trino.sql.planner.plan.TableWriterNode.CreateReference) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) LimitNode(io.trino.sql.planner.plan.LimitNode) TableLayout(io.trino.metadata.TableLayout) TypeCoercion(io.trino.type.TypeCoercion) BOOLEAN(io.trino.spi.type.BooleanType.BOOLEAN) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) StatsAndCosts(io.trino.cost.StatsAndCosts) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) VARCHAR(io.trino.spi.type.VarcharType.VARCHAR) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) PlanOptimizer(io.trino.sql.planner.optimizations.PlanOptimizer) NodeRef(io.trino.sql.tree.NodeRef) ColumnHandle(io.trino.spi.connector.ColumnHandle) AggregationNode(io.trino.sql.planner.plan.AggregationNode) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) VARBINARY(io.trino.spi.type.VarbinaryType.VARBINARY) Query(io.trino.sql.tree.Query) StringLiteral(io.trino.sql.tree.StringLiteral) TableStatisticAggregation(io.trino.sql.planner.StatisticsAggregationPlanner.TableStatisticAggregation) AggregationNode.singleGroupingSet(io.trino.sql.planner.plan.AggregationNode.singleGroupingSet) TableHandle(io.trino.metadata.TableHandle) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) CharType(io.trino.spi.type.CharType) Table(io.trino.sql.tree.Table) TableFinishNode(io.trino.sql.planner.plan.TableFinishNode) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) UnknownType(io.trino.type.UnknownType) RefreshMaterializedView(io.trino.sql.tree.RefreshMaterializedView) TableWriterNode(io.trino.sql.planner.plan.TableWriterNode) OPTIMIZED_AND_VALIDATED(io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED_AND_VALIDATED) Scope(io.trino.sql.analyzer.Scope) FilterNode(io.trino.sql.planner.plan.FilterNode) StatsCalculator(io.trino.cost.StatsCalculator) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) RelationId(io.trino.sql.analyzer.RelationId) DeleteNode(io.trino.sql.planner.plan.DeleteNode) Update(io.trino.sql.tree.Update) INTEGER(io.trino.spi.type.IntegerType.INTEGER) FunctionCall(io.trino.sql.tree.FunctionCall) ImmutableMap(com.google.common.collect.ImmutableMap) ResolvedFunction(io.trino.metadata.ResolvedFunction) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) TrinoException(io.trino.spi.TrinoException) ROW_COUNT(io.trino.spi.statistics.TableStatisticType.ROW_COUNT) TableExecuteHandle(io.trino.metadata.TableExecuteHandle) StatsProvider(io.trino.cost.StatsProvider) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) GenericLiteral(io.trino.sql.tree.GenericLiteral) Objects(java.util.Objects) TableMetadata(io.trino.metadata.TableMetadata) List(java.util.List) IfExpression(io.trino.sql.tree.IfExpression) BIGINT(io.trino.spi.type.BigintType.BIGINT) StandardErrorCode(io.trino.spi.StandardErrorCode) Analyze(io.trino.sql.tree.Analyze) Entry(java.util.Map.Entry) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) PlannerContext(io.trino.sql.PlannerContext) Analysis(io.trino.sql.analyzer.Analysis) PERMISSION_DENIED(io.trino.spi.StandardErrorCode.PERMISSION_DENIED) Logger(io.airlift.log.Logger) Type(io.trino.spi.type.Type) CreateTableAsSelect(io.trino.sql.tree.CreateTableAsSelect) HashMap(java.util.HashMap) StatisticAggregations(io.trino.sql.planner.plan.StatisticAggregations) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) OPTIMIZED(io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED) Function(java.util.function.Function) Cast(io.trino.sql.tree.Cast) VarcharType(io.trino.spi.type.VarcharType) CachingCostProvider(io.trino.cost.CachingCostProvider) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) Objects.requireNonNull(java.util.Objects.requireNonNull) RefreshMaterializedViewNode(io.trino.sql.planner.plan.RefreshMaterializedViewNode) NullLiteral(io.trino.sql.tree.NullLiteral) Field(io.trino.sql.analyzer.Field) GREATER_THAN_OR_EQUAL(io.trino.sql.tree.ComparisonExpression.Operator.GREATER_THAN_OR_EQUAL) ProjectNode(io.trino.sql.planner.plan.ProjectNode) DISTRIBUTED_PLAN_SANITY_CHECKER(io.trino.sql.planner.sanity.PlanSanityChecker.DISTRIBUTED_PLAN_SANITY_CHECKER) WriterTarget(io.trino.sql.planner.plan.TableWriterNode.WriterTarget) TRUE_LITERAL(io.trino.sql.tree.BooleanLiteral.TRUE_LITERAL) UpdateNode(io.trino.sql.planner.plan.UpdateNode) QualifiedName(io.trino.sql.tree.QualifiedName) CostCalculator(io.trino.cost.CostCalculator) WarningCollector(io.trino.execution.warnings.WarningCollector) Row(io.trino.sql.tree.Row) Metadata(io.trino.metadata.Metadata) Insert(io.trino.sql.tree.Insert) Streams.zip(com.google.common.collect.Streams.zip) TableStatisticsMetadata(io.trino.spi.statistics.TableStatisticsMetadata) ColumnMetadata(io.trino.spi.connector.ColumnMetadata) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) InsertReference(io.trino.sql.planner.plan.TableWriterNode.InsertReference) NodeRef(io.trino.sql.tree.NodeRef) Field(io.trino.sql.analyzer.Field) RelationType(io.trino.sql.analyzer.RelationType) ConnectorTableMetadata(io.trino.spi.connector.ConnectorTableMetadata) TableMetadata(io.trino.metadata.TableMetadata) ColumnHandle(io.trino.spi.connector.ColumnHandle) RelationType(io.trino.sql.analyzer.RelationType) CharType(io.trino.spi.type.CharType) UnknownType(io.trino.type.UnknownType) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) Type(io.trino.spi.type.Type) VarcharType(io.trino.spi.type.VarcharType) Scope(io.trino.sql.analyzer.Scope) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) IfExpression(io.trino.sql.tree.IfExpression) Expression(io.trino.sql.tree.Expression) ProjectNode(io.trino.sql.planner.plan.ProjectNode) NullLiteral(io.trino.sql.tree.NullLiteral)

Example 2 with RelationType

use of io.trino.sql.analyzer.RelationType in project trino by trinodb.

the class RelationPlanner method process.

private SetOperationPlan process(SetOperation node) {
    RelationType outputFields = analysis.getOutputDescriptor(node);
    List<Symbol> outputs = outputFields.getAllFields().stream().map(symbolAllocator::newSymbol).collect(toImmutableList());
    ImmutableListMultimap.Builder<Symbol, Symbol> symbolMapping = ImmutableListMultimap.builder();
    ImmutableList.Builder<PlanNode> sources = ImmutableList.builder();
    for (Relation child : node.getRelations()) {
        RelationPlan plan = process(child, null);
        NodeAndMappings planAndMappings;
        List<Type> types = analysis.getRelationCoercion(child);
        if (types == null) {
            // no coercion required, only prune invisible fields from child outputs
            planAndMappings = pruneInvisibleFields(plan, idAllocator);
        } else {
            // apply required coercion and prune invisible fields from child outputs
            planAndMappings = coerce(plan, types, symbolAllocator, idAllocator);
        }
        for (int i = 0; i < outputFields.getAllFields().size(); i++) {
            symbolMapping.put(outputs.get(i), planAndMappings.getFields().get(i));
        }
        sources.add(planAndMappings.getNode());
    }
    return new SetOperationPlan(sources.build(), symbolMapping.build());
}
Also used : ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) AliasedRelation(io.trino.sql.tree.AliasedRelation) SampledRelation(io.trino.sql.tree.SampledRelation) Relation(io.trino.sql.tree.Relation) PatternRecognitionRelation(io.trino.sql.tree.PatternRecognitionRelation) RelationType(io.trino.sql.analyzer.RelationType) RowType(io.trino.spi.type.RowType) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) Type(io.trino.spi.type.Type) PlanNode(io.trino.sql.planner.plan.PlanNode) RelationType(io.trino.sql.analyzer.RelationType) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap)

Example 3 with RelationType

use of io.trino.sql.analyzer.RelationType in project trino by trinodb.

the class SubqueryPlanner method planScalarSubquery.

private PlanBuilder planScalarSubquery(PlanBuilder subPlan, Cluster<SubqueryExpression> cluster) {
    // Plan one of the predicates from the cluster
    SubqueryExpression scalarSubquery = cluster.getRepresentative();
    RelationPlan relationPlan = planSubquery(scalarSubquery, subPlan.getTranslations());
    PlanBuilder subqueryPlan = newPlanBuilder(relationPlan, analysis, lambdaDeclarationToSymbolMap);
    PlanNode root = new EnforceSingleRowNode(idAllocator.getNextId(), subqueryPlan.getRoot());
    Type type = analysis.getType(scalarSubquery);
    RelationType descriptor = relationPlan.getDescriptor();
    List<Symbol> fieldMappings = relationPlan.getFieldMappings();
    Symbol column;
    if (descriptor.getVisibleFieldCount() > 1) {
        column = symbolAllocator.newSymbol("row", type);
        ImmutableList.Builder<Expression> fields = ImmutableList.builder();
        for (int i = 0; i < descriptor.getAllFieldCount(); i++) {
            Field field = descriptor.getFieldByIndex(i);
            if (!field.isHidden()) {
                fields.add(fieldMappings.get(i).toSymbolReference());
            }
        }
        Expression expression = new Cast(new Row(fields.build()), TypeSignatureTranslator.toSqlType(type));
        root = new ProjectNode(idAllocator.getNextId(), root, Assignments.of(column, expression));
    } else {
        column = getOnlyElement(fieldMappings);
    }
    return appendCorrelatedJoin(subPlan, root, scalarSubquery.getQuery(), CorrelatedJoinNode.Type.INNER, TRUE_LITERAL, mapAll(cluster, subPlan.getScope(), column));
}
Also used : Cast(io.trino.sql.tree.Cast) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) Field(io.trino.sql.analyzer.Field) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) RelationType(io.trino.sql.analyzer.RelationType) Type(io.trino.spi.type.Type) PlanNode(io.trino.sql.planner.plan.PlanNode) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) QuantifiedComparisonExpression(io.trino.sql.tree.QuantifiedComparisonExpression) Expression(io.trino.sql.tree.Expression) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) NotExpression(io.trino.sql.tree.NotExpression) EnforceSingleRowNode(io.trino.sql.planner.plan.EnforceSingleRowNode) RelationType(io.trino.sql.analyzer.RelationType) ProjectNode(io.trino.sql.planner.plan.ProjectNode) Row(io.trino.sql.tree.Row)

Example 4 with RelationType

use of io.trino.sql.analyzer.RelationType in project trino by trinodb.

the class SubqueryPlanner method planSubquery.

private PlanAndMappings planSubquery(Expression subquery, Optional<Type> coercion, TranslationMap outerContext) {
    Type type = analysis.getType(subquery);
    Symbol column = symbolAllocator.newSymbol("row", type);
    RelationPlan relationPlan = planSubquery(subquery, outerContext);
    PlanBuilder subqueryPlan = newPlanBuilder(relationPlan, analysis, lambdaDeclarationToSymbolMap, ImmutableMap.of(scopeAwareKey(subquery, analysis, relationPlan.getScope()), column));
    RelationType descriptor = relationPlan.getDescriptor();
    ImmutableList.Builder<Expression> fields = ImmutableList.builder();
    for (int i = 0; i < descriptor.getAllFieldCount(); i++) {
        Field field = descriptor.getFieldByIndex(i);
        if (!field.isHidden()) {
            fields.add(relationPlan.getFieldMappings().get(i).toSymbolReference());
        }
    }
    subqueryPlan = subqueryPlan.withNewRoot(new ProjectNode(idAllocator.getNextId(), relationPlan.getRoot(), Assignments.of(column, new Cast(new Row(fields.build()), toSqlType(type)))));
    return coerceIfNecessary(subqueryPlan, column, subquery, analysis.getType(subquery), coercion);
}
Also used : Cast(io.trino.sql.tree.Cast) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) Field(io.trino.sql.analyzer.Field) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) RelationType(io.trino.sql.analyzer.RelationType) Type(io.trino.spi.type.Type) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) QuantifiedComparisonExpression(io.trino.sql.tree.QuantifiedComparisonExpression) Expression(io.trino.sql.tree.Expression) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) NotExpression(io.trino.sql.tree.NotExpression) RelationType(io.trino.sql.analyzer.RelationType) ProjectNode(io.trino.sql.planner.plan.ProjectNode) Row(io.trino.sql.tree.Row)

Example 5 with RelationType

use of io.trino.sql.analyzer.RelationType in project trino by trinodb.

the class RelationPlanner method planJoin.

private RelationPlan planJoin(Expression criteria, Join.Type type, Scope scope, RelationPlan leftPlan, RelationPlan rightPlan, Analysis.SubqueryAnalysis subqueries) {
    // NOTE: symbols must be in the same order as the outputDescriptor
    List<Symbol> outputSymbols = ImmutableList.<Symbol>builder().addAll(leftPlan.getFieldMappings()).addAll(rightPlan.getFieldMappings()).build();
    PlanBuilder leftPlanBuilder = newPlanBuilder(leftPlan, analysis, lambdaDeclarationToSymbolMap).withScope(scope, outputSymbols);
    PlanBuilder rightPlanBuilder = newPlanBuilder(rightPlan, analysis, lambdaDeclarationToSymbolMap).withScope(scope, outputSymbols);
    ImmutableList.Builder<JoinNode.EquiJoinClause> equiClauses = ImmutableList.builder();
    List<Expression> complexJoinExpressions = new ArrayList<>();
    List<Expression> postInnerJoinConditions = new ArrayList<>();
    RelationType left = leftPlan.getDescriptor();
    RelationType right = rightPlan.getDescriptor();
    if (type != CROSS && type != IMPLICIT) {
        List<Expression> leftComparisonExpressions = new ArrayList<>();
        List<Expression> rightComparisonExpressions = new ArrayList<>();
        List<ComparisonExpression.Operator> joinConditionComparisonOperators = new ArrayList<>();
        for (Expression conjunct : ExpressionUtils.extractConjuncts(criteria)) {
            if (!isEqualComparisonExpression(conjunct) && type != INNER) {
                complexJoinExpressions.add(conjunct);
                continue;
            }
            Set<QualifiedName> dependencies = SymbolsExtractor.extractNames(conjunct, analysis.getColumnReferences());
            if (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.
                complexJoinExpressions.add(conjunct);
            } else if (conjunct instanceof ComparisonExpression) {
                Expression firstExpression = ((ComparisonExpression) conjunct).getLeft();
                Expression secondExpression = ((ComparisonExpression) conjunct).getRight();
                ComparisonExpression.Operator comparisonOperator = ((ComparisonExpression) conjunct).getOperator();
                Set<QualifiedName> firstDependencies = SymbolsExtractor.extractNames(firstExpression, analysis.getColumnReferences());
                Set<QualifiedName> secondDependencies = SymbolsExtractor.extractNames(secondExpression, analysis.getColumnReferences());
                if (firstDependencies.stream().allMatch(left::canResolve) && secondDependencies.stream().allMatch(right::canResolve)) {
                    leftComparisonExpressions.add(firstExpression);
                    rightComparisonExpressions.add(secondExpression);
                    joinConditionComparisonOperators.add(comparisonOperator);
                } else if (firstDependencies.stream().allMatch(right::canResolve) && secondDependencies.stream().allMatch(left::canResolve)) {
                    leftComparisonExpressions.add(secondExpression);
                    rightComparisonExpressions.add(firstExpression);
                    joinConditionComparisonOperators.add(comparisonOperator.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, subqueries);
        rightPlanBuilder = subqueryPlanner.handleSubqueries(rightPlanBuilder, rightComparisonExpressions, subqueries);
        // Add projections for join criteria
        leftPlanBuilder = leftPlanBuilder.appendProjections(leftComparisonExpressions, symbolAllocator, idAllocator);
        rightPlanBuilder = rightPlanBuilder.appendProjections(rightComparisonExpressions, symbolAllocator, idAllocator);
        QueryPlanner.PlanAndMappings leftCoercions = coerce(leftPlanBuilder, leftComparisonExpressions, analysis, idAllocator, symbolAllocator, typeCoercion);
        leftPlanBuilder = leftCoercions.getSubPlan();
        QueryPlanner.PlanAndMappings rightCoercions = coerce(rightPlanBuilder, rightComparisonExpressions, analysis, idAllocator, symbolAllocator, typeCoercion);
        rightPlanBuilder = rightCoercions.getSubPlan();
        for (int i = 0; i < leftComparisonExpressions.size(); i++) {
            if (joinConditionComparisonOperators.get(i) == ComparisonExpression.Operator.EQUAL) {
                Symbol leftSymbol = leftCoercions.get(leftComparisonExpressions.get(i));
                Symbol rightSymbol = rightCoercions.get(rightComparisonExpressions.get(i));
                equiClauses.add(new JoinNode.EquiJoinClause(leftSymbol, rightSymbol));
            } else {
                postInnerJoinConditions.add(new ComparisonExpression(joinConditionComparisonOperators.get(i), leftCoercions.get(leftComparisonExpressions.get(i)).toSymbolReference(), rightCoercions.get(rightComparisonExpressions.get(i)).toSymbolReference()));
            }
        }
    }
    PlanNode root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(type), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), leftPlanBuilder.getRoot().getOutputSymbols(), rightPlanBuilder.getRoot().getOutputSymbols(), false, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), ImmutableMap.of(), Optional.empty());
    if (type != INNER) {
        for (Expression complexExpression : complexJoinExpressions) {
            Set<QualifiedName> dependencies = SymbolsExtractor.extractNamesNoSubqueries(complexExpression, analysis.getColumnReferences());
            // t JOIN u ON t.x + u.x = (...) get's planned on an arbitrary side
            if (dependencies.stream().allMatch(left::canResolve)) {
                leftPlanBuilder = subqueryPlanner.handleSubqueries(leftPlanBuilder, complexExpression, subqueries);
            } else {
                rightPlanBuilder = subqueryPlanner.handleSubqueries(rightPlanBuilder, complexExpression, subqueries);
            }
        }
    }
    TranslationMap translationMap = new TranslationMap(outerContext, scope, analysis, lambdaDeclarationToSymbolMap, outputSymbols).withAdditionalMappings(leftPlanBuilder.getTranslations().getMappings()).withAdditionalMappings(rightPlanBuilder.getTranslations().getMappings());
    if (type != INNER && !complexJoinExpressions.isEmpty()) {
        Expression joinedFilterCondition = ExpressionUtils.and(complexJoinExpressions);
        Expression rewrittenFilterCondition = translationMap.rewrite(joinedFilterCondition);
        root = new JoinNode(idAllocator.getNextId(), JoinNode.Type.typeConvert(type), leftPlanBuilder.getRoot(), rightPlanBuilder.getRoot(), equiClauses.build(), leftPlanBuilder.getRoot().getOutputSymbols(), rightPlanBuilder.getRoot().getOutputSymbols(), false, Optional.of(rewrittenFilterCondition), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), ImmutableMap.of(), Optional.empty());
    }
    if (type == INNER) {
        // rewrite all the other conditions using output symbols from left + right plan node.
        PlanBuilder rootPlanBuilder = new PlanBuilder(translationMap, root);
        rootPlanBuilder = subqueryPlanner.handleSubqueries(rootPlanBuilder, complexJoinExpressions, subqueries);
        for (Expression expression : complexJoinExpressions) {
            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, scope, outputSymbols, outerContext);
}
Also used : Set(java.util.Set) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) AggregationNode.singleGroupingSet(io.trino.sql.planner.plan.AggregationNode.singleGroupingSet) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) FilterNode(io.trino.sql.planner.plan.FilterNode) ArrayList(java.util.ArrayList) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) PlanNode(io.trino.sql.planner.plan.PlanNode) RelationType(io.trino.sql.analyzer.RelationType) CorrelatedJoinNode(io.trino.sql.planner.plan.CorrelatedJoinNode) JoinNode(io.trino.sql.planner.plan.JoinNode) QualifiedName(io.trino.sql.tree.QualifiedName) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) Expression(io.trino.sql.tree.Expression) SubqueryExpression(io.trino.sql.tree.SubqueryExpression)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)7 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)7 RelationType (io.trino.sql.analyzer.RelationType)7 Field (io.trino.sql.analyzer.Field)5 PlanNode (io.trino.sql.planner.plan.PlanNode)5 Type (io.trino.spi.type.Type)4 TypeSignatureTranslator.toSqlType (io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType)4 PlanBuilder.newPlanBuilder (io.trino.sql.planner.PlanBuilder.newPlanBuilder)4 ComparisonExpression (io.trino.sql.tree.ComparisonExpression)4 Expression (io.trino.sql.tree.Expression)4 ProjectNode (io.trino.sql.planner.plan.ProjectNode)3 Cast (io.trino.sql.tree.Cast)3 Row (io.trino.sql.tree.Row)3 SubqueryExpression (io.trino.sql.tree.SubqueryExpression)3 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)2 NotExpression (io.trino.sql.tree.NotExpression)2 QuantifiedComparisonExpression (io.trino.sql.tree.QuantifiedComparisonExpression)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 Verify.verify (com.google.common.base.Verify.verify)1 ImmutableListMultimap (com.google.common.collect.ImmutableListMultimap)1