Search in sources :

Example 6 with Analysis

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

the class QueryPlanner method plan.

public UpdateNode plan(Update node) {
    Table table = node.getTable();
    TableHandle handle = analysis.getTableHandle(table);
    TableSchema tableSchema = plannerContext.getMetadata().getTableSchema(session, handle);
    Map<String, ColumnHandle> columnMap = plannerContext.getMetadata().getColumnHandles(session, handle);
    List<ColumnSchema> columnsSchemas = tableSchema.getColumns();
    List<String> targetColumnNames = node.getAssignments().stream().map(assignment -> assignment.getName().getValue()).collect(toImmutableList());
    // Create lists of columnnames and SET expressions, in table column order
    ImmutableList.Builder<String> updatedColumnNamesBuilder = ImmutableList.builder();
    ImmutableList.Builder<ColumnHandle> updatedColumnHandlesBuilder = ImmutableList.builder();
    ImmutableList.Builder<Expression> orderedColumnValuesBuilder = ImmutableList.builder();
    for (ColumnSchema columnSchema : columnsSchemas) {
        String name = columnSchema.getName();
        int index = targetColumnNames.indexOf(name);
        if (index >= 0) {
            updatedColumnNamesBuilder.add(name);
            updatedColumnHandlesBuilder.add(requireNonNull(columnMap.get(name), "columnMap didn't contain name"));
            orderedColumnValuesBuilder.add(node.getAssignments().get(index).getValue());
        }
    }
    List<String> updatedColumnNames = updatedColumnNamesBuilder.build();
    List<ColumnHandle> updatedColumnHandles = updatedColumnHandlesBuilder.build();
    List<Expression> orderedColumnValues = orderedColumnValuesBuilder.build();
    // create table scan
    RelationPlan relationPlan = new RelationPlanner(analysis, symbolAllocator, idAllocator, lambdaDeclarationToSymbolMap, plannerContext, outerContext, session, recursiveSubqueries).process(table, null);
    PlanBuilder builder = newPlanBuilder(relationPlan, analysis, lambdaDeclarationToSymbolMap);
    if (node.getWhere().isPresent()) {
        builder = filter(builder, node.getWhere().get(), node);
    }
    builder = subqueryPlanner.handleSubqueries(builder, orderedColumnValues, analysis.getSubqueries(node));
    builder = builder.appendProjections(orderedColumnValues, symbolAllocator, idAllocator);
    PlanAndMappings planAndMappings = coerce(builder, orderedColumnValues, analysis, idAllocator, symbolAllocator, typeCoercion);
    builder = planAndMappings.getSubPlan();
    ImmutableList.Builder<Symbol> updatedColumnValuesBuilder = ImmutableList.builder();
    orderedColumnValues.forEach(columnValue -> updatedColumnValuesBuilder.add(planAndMappings.get(columnValue)));
    Symbol rowId = builder.translate(analysis.getRowIdField(table));
    updatedColumnValuesBuilder.add(rowId);
    List<Symbol> outputs = ImmutableList.of(symbolAllocator.newSymbol("partialrows", BIGINT), symbolAllocator.newSymbol("fragment", VARBINARY));
    Optional<PlanNodeId> tableScanId = getIdForLeftTableScan(relationPlan.getRoot());
    checkArgument(tableScanId.isPresent(), "tableScanId not present");
    // create update node
    return new UpdateNode(idAllocator.getNextId(), builder.getRoot(), new UpdateTarget(Optional.empty(), plannerContext.getMetadata().getTableMetadata(session, handle).getTable(), updatedColumnNames, updatedColumnHandles), rowId, updatedColumnValuesBuilder.build(), outputs);
}
Also used : PatternRecognitionComponents(io.trino.sql.planner.RelationPlanner.PatternRecognitionComponents) Arrays(java.util.Arrays) TypeSignatureProvider.fromTypes(io.trino.sql.analyzer.TypeSignatureProvider.fromTypes) Delete(io.trino.sql.tree.Delete) PlanNode(io.trino.sql.planner.plan.PlanNode) Node(io.trino.sql.tree.Node) Offset(io.trino.sql.tree.Offset) PlanNodeId(io.trino.sql.planner.plan.PlanNodeId) LongLiteral(io.trino.sql.tree.LongLiteral) Map(java.util.Map) Union(io.trino.sql.tree.Union) FetchFirst(io.trino.sql.tree.FetchFirst) TableScanNode(io.trino.sql.planner.plan.TableScanNode) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) Set(java.util.Set) TableSchema(io.trino.metadata.TableSchema) SortItem(io.trino.sql.tree.SortItem) NodeUtils.getSortItemsFromOrderBy(io.trino.sql.NodeUtils.getSortItemsFromOrderBy) DEFAULT_FRAME(io.trino.sql.planner.plan.WindowNode.Frame.DEFAULT_FRAME) RelationType(io.trino.sql.analyzer.RelationType) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) AggregationNode.groupingSets(io.trino.sql.planner.plan.AggregationNode.groupingSets) DeleteTarget(io.trino.sql.planner.plan.TableWriterNode.DeleteTarget) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) DecimalLiteral(io.trino.sql.tree.DecimalLiteral) ValuesNode(io.trino.sql.planner.plan.ValuesNode) ExpressionAnalyzer.isNumericType(io.trino.sql.analyzer.ExpressionAnalyzer.isNumericType) Session(io.trino.Session) Iterables(com.google.common.collect.Iterables) LimitNode(io.trino.sql.planner.plan.LimitNode) TypeCoercion(io.trino.type.TypeCoercion) BOOLEAN(io.trino.spi.type.BooleanType.BOOLEAN) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) UpdateTarget(io.trino.sql.planner.plan.TableWriterNode.UpdateTarget) ScopeAware.scopeAwareKey(io.trino.sql.planner.ScopeAware.scopeAwareKey) VARCHAR(io.trino.spi.type.VarcharType.VARCHAR) 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) GroupingOperationRewriter.rewriteGroupingOperation(io.trino.sql.planner.GroupingOperationRewriter.rewriteGroupingOperation) NodeUtils(io.trino.sql.NodeUtils) INTERVAL_DAY_TIME(io.trino.type.IntervalDayTimeType.INTERVAL_DAY_TIME) Query(io.trino.sql.tree.Query) StringLiteral(io.trino.sql.tree.StringLiteral) Relation(io.trino.sql.tree.Relation) GroupingSetAnalysis(io.trino.sql.analyzer.Analysis.GroupingSetAnalysis) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) SortOrder(io.trino.spi.connector.SortOrder) AggregationNode.singleGroupingSet(io.trino.sql.planner.plan.AggregationNode.singleGroupingSet) TableHandle(io.trino.metadata.TableHandle) Table(io.trino.sql.tree.Table) GroupIdNode(io.trino.sql.planner.plan.GroupIdNode) YEAR(io.trino.sql.tree.IntervalLiteral.IntervalField.YEAR) OffsetNode(io.trino.sql.planner.plan.OffsetNode) ROWS(io.trino.sql.tree.WindowFrame.Type.ROWS) NullTreatment(io.trino.sql.tree.FunctionCall.NullTreatment) DAY(io.trino.sql.tree.IntervalLiteral.IntervalField.DAY) MeasureDefinition(io.trino.sql.tree.MeasureDefinition) INTERVAL_YEAR_MONTH(io.trino.type.IntervalYearMonthType.INTERVAL_YEAR_MONTH) Aggregation(io.trino.sql.planner.plan.AggregationNode.Aggregation) FilterNode(io.trino.sql.planner.plan.FilterNode) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OrderingScheme.sortItemToSortOrder(io.trino.sql.planner.OrderingScheme.sortItemToSortOrder) SelectExpression(io.trino.sql.analyzer.Analysis.SelectExpression) GROUPS(io.trino.sql.tree.WindowFrame.Type.GROUPS) DeleteNode(io.trino.sql.planner.plan.DeleteNode) Update(io.trino.sql.tree.Update) FunctionCall(io.trino.sql.tree.FunctionCall) QuerySpecification(io.trino.sql.tree.QuerySpecification) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) ResolvedFunction(io.trino.metadata.ResolvedFunction) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) IntervalLiteral(io.trino.sql.tree.IntervalLiteral) RANGE(io.trino.sql.tree.WindowFrame.Type.RANGE) VariableDefinition(io.trino.sql.tree.VariableDefinition) PatternRecognitionNode(io.trino.sql.planner.plan.PatternRecognitionNode) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) LESS_THAN_OR_EQUAL(io.trino.sql.tree.ComparisonExpression.Operator.LESS_THAN_OR_EQUAL) GenericLiteral(io.trino.sql.tree.GenericLiteral) SimplePlanRewriter(io.trino.sql.planner.plan.SimplePlanRewriter) List(java.util.List) POSITIVE(io.trino.sql.tree.IntervalLiteral.Sign.POSITIVE) IfExpression(io.trino.sql.tree.IfExpression) ColumnSchema(io.trino.spi.connector.ColumnSchema) BIGINT(io.trino.spi.type.BigintType.BIGINT) WindowFrame(io.trino.sql.tree.WindowFrame) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) WindowNode(io.trino.sql.planner.plan.WindowNode) DecimalType(io.trino.spi.type.DecimalType) OrderBy(io.trino.sql.tree.OrderBy) PlannerContext(io.trino.sql.PlannerContext) Analysis(io.trino.sql.analyzer.Analysis) IntStream(java.util.stream.IntStream) FieldId(io.trino.sql.analyzer.FieldId) UnionNode(io.trino.sql.planner.plan.UnionNode) WindowOperation(io.trino.sql.tree.WindowOperation) Type(io.trino.spi.type.Type) LambdaExpression(io.trino.sql.tree.LambdaExpression) HashMap(java.util.HashMap) SystemSessionProperties.getMaxRecursionDepth(io.trino.SystemSessionProperties.getMaxRecursionDepth) SortNode(io.trino.sql.planner.plan.SortNode) Function(java.util.function.Function) Cast(io.trino.sql.tree.Cast) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) GREATER_THAN_OR_EQUAL(io.trino.sql.tree.ComparisonExpression.Operator.GREATER_THAN_OR_EQUAL) ProjectNode(io.trino.sql.planner.plan.ProjectNode) ResolvedWindow(io.trino.sql.analyzer.Analysis.ResolvedWindow) RowsPerMatch(io.trino.sql.tree.PatternRecognitionRelation.RowsPerMatch) Iterator(java.util.Iterator) TRUE_LITERAL(io.trino.sql.tree.BooleanLiteral.TRUE_LITERAL) UpdateNode(io.trino.sql.planner.plan.UpdateNode) QualifiedName(io.trino.sql.tree.QualifiedName) SystemSessionProperties.isSkipRedundantSort(io.trino.SystemSessionProperties.isSkipRedundantSort) FrameBound(io.trino.sql.tree.FrameBound) TableSchema(io.trino.metadata.TableSchema) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) ColumnSchema(io.trino.spi.connector.ColumnSchema) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) PlanNodeId(io.trino.sql.planner.plan.PlanNodeId) UpdateNode(io.trino.sql.planner.plan.UpdateNode) ColumnHandle(io.trino.spi.connector.ColumnHandle) Table(io.trino.sql.tree.Table) UpdateTarget(io.trino.sql.planner.plan.TableWriterNode.UpdateTarget) SelectExpression(io.trino.sql.analyzer.Analysis.SelectExpression) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) IfExpression(io.trino.sql.tree.IfExpression) Expression(io.trino.sql.tree.Expression) LambdaExpression(io.trino.sql.tree.LambdaExpression) TableHandle(io.trino.metadata.TableHandle)

Example 7 with Analysis

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

the class RelationPlanner method visitValues.

@Override
protected RelationPlan visitValues(Values node, Void context) {
    Scope scope = analysis.getScope(node);
    ImmutableList.Builder<Symbol> outputSymbolsBuilder = ImmutableList.builder();
    for (Field field : scope.getRelationType().getVisibleFields()) {
        Symbol symbol = symbolAllocator.newSymbol(field);
        outputSymbolsBuilder.add(symbol);
    }
    List<Symbol> outputSymbols = outputSymbolsBuilder.build();
    TranslationMap translationMap = new TranslationMap(outerContext, analysis.getScope(node), analysis, lambdaDeclarationToSymbolMap, outputSymbols);
    ImmutableList.Builder<Expression> rows = ImmutableList.builder();
    for (Expression row : node.getRows()) {
        if (row instanceof Row) {
            rows.add(new Row(((Row) row).getItems().stream().map(item -> coerceIfNecessary(analysis, item, translationMap.rewrite(item))).collect(toImmutableList())));
        } else if (analysis.getType(row) instanceof RowType) {
            rows.add(coerceIfNecessary(analysis, row, translationMap.rewrite(row)));
        } else {
            rows.add(new Row(ImmutableList.of(coerceIfNecessary(analysis, row, translationMap.rewrite(row)))));
        }
    }
    ValuesNode valuesNode = new ValuesNode(idAllocator.getNextId(), outputSymbols, rows.build());
    return new RelationPlan(valuesNode, scope, outputSymbols, outerContext);
}
Also used : ListMultimap(com.google.common.collect.ListMultimap) SubsetDefinition(io.trino.sql.tree.SubsetDefinition) CorrelatedJoinNode(io.trino.sql.planner.plan.CorrelatedJoinNode) PlanNode(io.trino.sql.planner.plan.PlanNode) SetOperation(io.trino.sql.tree.SetOperation) Values(io.trino.sql.tree.Values) NOT_SUPPORTED(io.trino.spi.StandardErrorCode.NOT_SUPPORTED) AliasedRelation(io.trino.sql.tree.AliasedRelation) Node(io.trino.sql.tree.Node) ONE(io.trino.sql.tree.PatternRecognitionRelation.RowsPerMatch.ONE) Map(java.util.Map) RowPattern(io.trino.sql.tree.RowPattern) Union(io.trino.sql.tree.Union) SemanticExceptions.semanticException(io.trino.sql.analyzer.SemanticExceptions.semanticException) ENGLISH(java.util.Locale.ENGLISH) TableScanNode(io.trino.sql.planner.plan.TableScanNode) Identifier(io.trino.sql.tree.Identifier) Lateral(io.trino.sql.tree.Lateral) SampledRelation(io.trino.sql.tree.SampledRelation) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Assignments(io.trino.sql.planner.plan.Assignments) Join(io.trino.sql.tree.Join) Set(java.util.Set) PAST_LAST(io.trino.sql.tree.SkipTo.Position.PAST_LAST) SortItem(io.trino.sql.tree.SortItem) NodeUtils.getSortItemsFromOrderBy(io.trino.sql.NodeUtils.getSortItemsFromOrderBy) RelationType(io.trino.sql.analyzer.RelationType) IntersectNode(io.trino.sql.planner.plan.IntersectNode) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) QueryPlanner.pruneInvisibleFields(io.trino.sql.planner.QueryPlanner.pruneInvisibleFields) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) IrRowPattern(io.trino.sql.planner.rowpattern.ir.IrRowPattern) ValuesNode(io.trino.sql.planner.plan.ValuesNode) TRUE(java.lang.Boolean.TRUE) Session(io.trino.Session) SkipTo(io.trino.sql.tree.SkipTo) TypeCoercion(io.trino.type.TypeCoercion) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) NodeRef(io.trino.sql.tree.NodeRef) INNER(io.trino.sql.tree.Join.Type.INNER) ColumnHandle(io.trino.spi.connector.ColumnHandle) AggregationNode(io.trino.sql.planner.plan.AggregationNode) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Query(io.trino.sql.tree.Query) ExpressionUtils(io.trino.sql.ExpressionUtils) Relation(io.trino.sql.tree.Relation) IrLabel(io.trino.sql.planner.rowpattern.ir.IrLabel) PatternRecognitionRelation(io.trino.sql.tree.PatternRecognitionRelation) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) UnnestNode(io.trino.sql.planner.plan.UnnestNode) AggregationNode.singleGroupingSet(io.trino.sql.planner.plan.AggregationNode.singleGroupingSet) TableHandle(io.trino.metadata.TableHandle) ExceptNode(io.trino.sql.planner.plan.ExceptNode) RowPatternToIrRewriter(io.trino.sql.planner.rowpattern.RowPatternToIrRewriter) Table(io.trino.sql.tree.Table) SampleNode(io.trino.sql.planner.plan.SampleNode) MeasureDefinition(io.trino.sql.tree.MeasureDefinition) Intersect(io.trino.sql.tree.Intersect) Scope(io.trino.sql.analyzer.Scope) FilterNode(io.trino.sql.planner.plan.FilterNode) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) IMPLICIT(io.trino.sql.tree.Join.Type.IMPLICIT) UnnestAnalysis(io.trino.sql.analyzer.Analysis.UnnestAnalysis) QueryPlanner.coerce(io.trino.sql.planner.QueryPlanner.coerce) TableSubquery(io.trino.sql.tree.TableSubquery) JoinNode(io.trino.sql.planner.plan.JoinNode) QueryPlanner.planWindowSpecification(io.trino.sql.planner.QueryPlanner.planWindowSpecification) QuerySpecification(io.trino.sql.tree.QuerySpecification) RowType(io.trino.spi.type.RowType) ImmutableSet(com.google.common.collect.ImmutableSet) QueryPlanner.coerceIfNecessary(io.trino.sql.planner.QueryPlanner.coerceIfNecessary) ImmutableMap(com.google.common.collect.ImmutableMap) TypeSignatureTranslator.toSqlType(io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType) VariableDefinition(io.trino.sql.tree.VariableDefinition) PatternRecognitionNode(io.trino.sql.planner.plan.PatternRecognitionNode) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) CROSS(io.trino.sql.tree.Join.Type.CROSS) INITIAL(io.trino.sql.tree.PatternSearchMode.Mode.INITIAL) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) List(java.util.List) PatternSearchMode(io.trino.sql.tree.PatternSearchMode) NaturalJoin(io.trino.sql.tree.NaturalJoin) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) WindowNode(io.trino.sql.planner.plan.WindowNode) PlannerContext(io.trino.sql.PlannerContext) Analysis(io.trino.sql.analyzer.Analysis) UnionNode(io.trino.sql.planner.plan.UnionNode) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) Type(io.trino.spi.type.Type) Measure(io.trino.sql.planner.plan.PatternRecognitionNode.Measure) HashMap(java.util.HashMap) Unnest(io.trino.sql.tree.Unnest) Function(java.util.function.Function) Cast(io.trino.sql.tree.Cast) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) Field(io.trino.sql.analyzer.Field) ProjectNode(io.trino.sql.planner.plan.ProjectNode) ExpressionAndValuePointers(io.trino.sql.planner.rowpattern.LogicalIndexExtractor.ExpressionAndValuePointers) AstVisitor(io.trino.sql.tree.AstVisitor) JoinUsing(io.trino.sql.tree.JoinUsing) Except(io.trino.sql.tree.Except) LogicalIndexExtractor(io.trino.sql.planner.rowpattern.LogicalIndexExtractor) TRUE_LITERAL(io.trino.sql.tree.BooleanLiteral.TRUE_LITERAL) QualifiedName(io.trino.sql.tree.QualifiedName) QueryPlanner.extractPatternRecognitionExpressions(io.trino.sql.planner.QueryPlanner.extractPatternRecognitionExpressions) Row(io.trino.sql.tree.Row) JoinCriteria(io.trino.sql.tree.JoinCriteria) ValuesNode(io.trino.sql.planner.plan.ValuesNode) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) RowType(io.trino.spi.type.RowType) Field(io.trino.sql.analyzer.Field) Scope(io.trino.sql.analyzer.Scope) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) Expression(io.trino.sql.tree.Expression) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) Row(io.trino.sql.tree.Row)

Example 8 with Analysis

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

the class SubqueryPlanner method planQuantifiedComparison.

private PlanBuilder planQuantifiedComparison(PlanBuilder subPlan, Cluster<QuantifiedComparisonExpression> cluster, Analysis.SubqueryAnalysis subqueries) {
    // Plan one of the predicates from the cluster
    QuantifiedComparisonExpression quantifiedComparison = cluster.getRepresentative();
    ComparisonExpression.Operator operator = quantifiedComparison.getOperator();
    Quantifier quantifier = quantifiedComparison.getQuantifier();
    Expression value = quantifiedComparison.getValue();
    SubqueryExpression subquery = (SubqueryExpression) quantifiedComparison.getSubquery();
    subPlan = handleSubqueries(subPlan, value, subqueries);
    Symbol output = symbolAllocator.newSymbol(quantifiedComparison, BOOLEAN);
    Analysis.PredicateCoercions predicateCoercions = analysis.getPredicateCoercions(quantifiedComparison);
    switch(operator) {
        case EQUAL:
            switch(quantifier) {
                case ALL:
                    subPlan = planQuantifiedComparison(subPlan, operator, quantifier, value, subquery, output, predicateCoercions);
                    return new PlanBuilder(subPlan.getTranslations().withAdditionalMappings(ImmutableMap.of(scopeAwareKey(quantifiedComparison, analysis, subPlan.getScope()), output)), subPlan.getRoot());
                case ANY:
                case SOME:
                    // A = ANY B <=> A IN B
                    subPlan = planInPredicate(subPlan, value, subquery, output, quantifiedComparison, predicateCoercions);
                    return new PlanBuilder(subPlan.getTranslations().withAdditionalMappings(mapAll(cluster, subPlan.getScope(), output)), subPlan.getRoot());
            }
            break;
        case NOT_EQUAL:
            switch(quantifier) {
                case ALL:
                    {
                        // A <> ALL B <=> !(A IN B)
                        subPlan = planInPredicate(subPlan, value, subquery, output, quantifiedComparison, predicateCoercions);
                        return addNegation(subPlan, cluster, output);
                    }
                case ANY:
                case SOME:
                    {
                        // A <> ANY B <=> min B <> max B || A <> min B <=> !(min B = max B && A = min B) <=> !(A = ALL B)
                        // "A <> ANY B" is equivalent to "NOT (A = ALL B)" so add a rewrite for the initial quantifiedComparison to notAll
                        subPlan = planQuantifiedComparison(subPlan, EQUAL, Quantifier.ALL, value, subquery, output, predicateCoercions);
                        return addNegation(subPlan, cluster, output);
                    }
            }
            break;
        case LESS_THAN:
        case LESS_THAN_OR_EQUAL:
        case GREATER_THAN:
        case GREATER_THAN_OR_EQUAL:
            subPlan = planQuantifiedComparison(subPlan, operator, quantifier, value, subquery, output, predicateCoercions);
            return new PlanBuilder(subPlan.getTranslations().withAdditionalMappings(mapAll(cluster, subPlan.getScope(), output)), subPlan.getRoot());
        case IS_DISTINCT_FROM:
    }
    // all cases are checked, so this exception should never be thrown
    throw new IllegalArgumentException(format("Unexpected quantified comparison: '%s %s'", operator.getValue(), quantifier));
}
Also used : ComparisonExpression(io.trino.sql.tree.ComparisonExpression) QuantifiedComparisonExpression(io.trino.sql.tree.QuantifiedComparisonExpression) 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) Analysis(io.trino.sql.analyzer.Analysis) Quantifier(io.trino.sql.tree.QuantifiedComparisonExpression.Quantifier) QuantifiedComparisonExpression(io.trino.sql.tree.QuantifiedComparisonExpression) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) SubqueryExpression(io.trino.sql.tree.SubqueryExpression)

Example 9 with Analysis

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

the class LocalQueryRunner method createPlan.

public Plan createPlan(Session session, @Language("SQL") String sql, List<PlanOptimizer> optimizers, LogicalPlanner.Stage stage, WarningCollector warningCollector) {
    PreparedQuery preparedQuery = new QueryPreparer(sqlParser).prepareQuery(session, sql);
    assertFormattedSql(sqlParser, createParsingOptions(session), preparedQuery.getStatement());
    PlanNodeIdAllocator idAllocator = new PlanNodeIdAllocator();
    AnalyzerFactory analyzerFactory = createAnalyzerFactory(createQueryExplainerFactory(optimizers));
    Analyzer analyzer = analyzerFactory.createAnalyzer(session, preparedQuery.getParameters(), parameterExtractor(preparedQuery.getStatement(), preparedQuery.getParameters()), warningCollector);
    LogicalPlanner logicalPlanner = new LogicalPlanner(session, optimizers, new PlanSanityChecker(true), idAllocator, getPlannerContext(), new TypeAnalyzer(plannerContext, statementAnalyzerFactory), statsCalculator, costCalculator, warningCollector);
    Analysis analysis = analyzer.analyze(preparedQuery.getStatement());
    // make LocalQueryRunner always compute plan statistics for test purposes
    return logicalPlanner.plan(analysis, stage);
}
Also used : QueryPreparer(io.trino.execution.QueryPreparer) LogicalPlanner(io.trino.sql.planner.LogicalPlanner) PlanNodeIdAllocator(io.trino.sql.planner.PlanNodeIdAllocator) Analysis(io.trino.sql.analyzer.Analysis) PreparedQuery(io.trino.execution.QueryPreparer.PreparedQuery) PlanSanityChecker(io.trino.sql.planner.sanity.PlanSanityChecker) Analyzer(io.trino.sql.analyzer.Analyzer) TypeAnalyzer(io.trino.sql.planner.TypeAnalyzer) TypeAnalyzer(io.trino.sql.planner.TypeAnalyzer) StatementAnalyzerFactory(io.trino.sql.analyzer.StatementAnalyzerFactory) AnalyzerFactory(io.trino.sql.analyzer.AnalyzerFactory)

Example 10 with Analysis

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

the class CreateMaterializedViewTask method execute.

@Override
public ListenableFuture<Void> execute(CreateMaterializedView statement, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) {
    Session session = stateMachine.getSession();
    QualifiedObjectName name = createQualifiedObjectName(session, statement, statement.getName());
    Map<NodeRef<Parameter>, Expression> parameterLookup = parameterExtractor(statement, parameters);
    String sql = getFormattedSql(statement.getQuery(), sqlParser);
    Analysis analysis = analyzerFactory.createAnalyzer(session, parameters, parameterLookup, stateMachine.getWarningCollector()).analyze(statement);
    List<ViewColumn> columns = analysis.getOutputDescriptor(statement.getQuery()).getVisibleFields().stream().map(field -> new ViewColumn(field.getName().get(), field.getType().getTypeId())).collect(toImmutableList());
    CatalogName catalogName = getRequiredCatalogHandle(plannerContext.getMetadata(), session, statement, name.getCatalogName());
    Map<String, Object> properties = materializedViewPropertyManager.getProperties(catalogName, statement.getProperties(), session, plannerContext, accessControl, parameterLookup, true);
    MaterializedViewDefinition definition = new MaterializedViewDefinition(sql, session.getCatalog(), session.getSchema(), columns, statement.getComment(), session.getIdentity(), Optional.empty(), properties);
    accessControl.checkCanCreateMaterializedView(session.toSecurityContext(), name, properties);
    plannerContext.getMetadata().createMaterializedView(session, name, definition, statement.isReplace(), statement.isNotExists());
    stateMachine.setOutput(analysis.getTarget());
    stateMachine.setReferencedTables(analysis.getReferencedTables());
    return immediateVoidFuture();
}
Also used : ViewColumn(io.trino.metadata.ViewColumn) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AnalyzerFactory(io.trino.sql.analyzer.AnalyzerFactory) ParameterUtils.parameterExtractor(io.trino.sql.ParameterUtils.parameterExtractor) Inject(javax.inject.Inject) CatalogName(io.trino.connector.CatalogName) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) SqlParser(io.trino.sql.parser.SqlParser) Futures.immediateVoidFuture(com.google.common.util.concurrent.Futures.immediateVoidFuture) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) MetadataUtil.getRequiredCatalogHandle(io.trino.metadata.MetadataUtil.getRequiredCatalogHandle) CreateMaterializedView(io.trino.sql.tree.CreateMaterializedView) List(java.util.List) FeaturesConfig(io.trino.FeaturesConfig) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) AccessControl(io.trino.security.AccessControl) Parameter(io.trino.sql.tree.Parameter) SqlFormatterUtil.getFormattedSql(io.trino.sql.SqlFormatterUtil.getFormattedSql) WarningCollector(io.trino.execution.warnings.WarningCollector) MaterializedViewDefinition(io.trino.metadata.MaterializedViewDefinition) MaterializedViewPropertyManager(io.trino.metadata.MaterializedViewPropertyManager) Optional(java.util.Optional) Expression(io.trino.sql.tree.Expression) Session(io.trino.Session) PlannerContext(io.trino.sql.PlannerContext) Analysis(io.trino.sql.analyzer.Analysis) ViewColumn(io.trino.metadata.ViewColumn) MetadataUtil.createQualifiedObjectName(io.trino.metadata.MetadataUtil.createQualifiedObjectName) QualifiedObjectName(io.trino.metadata.QualifiedObjectName) NodeRef(io.trino.sql.tree.NodeRef) Expression(io.trino.sql.tree.Expression) MaterializedViewDefinition(io.trino.metadata.MaterializedViewDefinition) Analysis(io.trino.sql.analyzer.Analysis) CatalogName(io.trino.connector.CatalogName) Session(io.trino.Session)

Aggregations

Analysis (io.trino.sql.analyzer.Analysis)17 Expression (io.trino.sql.tree.Expression)12 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)11 Session (io.trino.Session)11 TableHandle (io.trino.metadata.TableHandle)11 Query (io.trino.sql.tree.Query)11 List (java.util.List)11 Objects.requireNonNull (java.util.Objects.requireNonNull)11 Optional (java.util.Optional)11 PlannerContext (io.trino.sql.PlannerContext)10 PlanBuilder.newPlanBuilder (io.trino.sql.planner.PlanBuilder.newPlanBuilder)10 PlanNode (io.trino.sql.planner.plan.PlanNode)10 ComparisonExpression (io.trino.sql.tree.ComparisonExpression)10 NodeRef (io.trino.sql.tree.NodeRef)10 Map (java.util.Map)10 ImmutableList (com.google.common.collect.ImmutableList)9 ImmutableMap (com.google.common.collect.ImmutableMap)9 ImmutableMap.toImmutableMap (com.google.common.collect.ImmutableMap.toImmutableMap)9 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)9 ColumnHandle (io.trino.spi.connector.ColumnHandle)9