Search in sources :

Example 1 with Node

use of io.trino.sql.tree.Node in project trino by trinodb.

the class QueryPlanner method planGroupingSets.

private GroupingSetsPlan planGroupingSets(PlanBuilder subPlan, QuerySpecification node, GroupingSetAnalysis groupingSetAnalysis) {
    Map<Symbol, Symbol> groupingSetMappings = new LinkedHashMap<>();
    // Compute a set of artificial columns that will contain the values of the original columns
    // filtered by whether the column is included in the grouping set
    // This will become the basis for the scope for any column references
    Symbol[] fields = new Symbol[subPlan.getTranslations().getFieldSymbols().size()];
    for (FieldId field : groupingSetAnalysis.getAllFields()) {
        Symbol input = subPlan.getTranslations().getFieldSymbols().get(field.getFieldIndex());
        Symbol output = symbolAllocator.newSymbol(input, "gid");
        fields[field.getFieldIndex()] = output;
        groupingSetMappings.put(output, input);
    }
    Map<ScopeAware<Expression>, Symbol> complexExpressions = new HashMap<>();
    for (Expression expression : groupingSetAnalysis.getComplexExpressions()) {
        if (!complexExpressions.containsKey(scopeAwareKey(expression, analysis, subPlan.getScope()))) {
            Symbol input = subPlan.translate(expression);
            Symbol output = symbolAllocator.newSymbol(expression, analysis.getType(expression), "gid");
            complexExpressions.put(scopeAwareKey(expression, analysis, subPlan.getScope()), output);
            groupingSetMappings.put(output, input);
        }
    }
    // For the purpose of "distinct", we need to canonicalize column references that may have varying
    // syntactic forms (e.g., "t.a" vs "a"). Thus we need to enumerate grouping sets based on the underlying
    // fieldId associated with each column reference expression.
    // The catch is that simple group-by expressions can be arbitrary expressions (this is a departure from the SQL specification).
    // But, they don't affect the number of grouping sets or the behavior of "distinct" . We can compute all the candidate
    // grouping sets in terms of fieldId, dedup as appropriate and then cross-join them with the complex expressions.
    // This tracks the grouping sets before complex expressions are considered.
    // It's also used to compute the descriptors needed to implement grouping()
    List<Set<FieldId>> columnOnlyGroupingSets = enumerateGroupingSets(groupingSetAnalysis);
    if (node.getGroupBy().isPresent() && node.getGroupBy().get().isDistinct()) {
        columnOnlyGroupingSets = columnOnlyGroupingSets.stream().distinct().collect(toImmutableList());
    }
    // translate from FieldIds to Symbols
    List<List<Symbol>> sets = columnOnlyGroupingSets.stream().map(set -> set.stream().map(FieldId::getFieldIndex).map(index -> fields[index]).collect(toImmutableList())).collect(toImmutableList());
    // combine (cartesian product) with complex expressions
    List<List<Symbol>> groupingSets = sets.stream().map(set -> ImmutableList.<Symbol>builder().addAll(set).addAll(complexExpressions.values()).build()).collect(toImmutableList());
    // Generate GroupIdNode (multiple grouping sets) or ProjectNode (single grouping set)
    PlanNode groupId;
    Optional<Symbol> groupIdSymbol = Optional.empty();
    if (groupingSets.size() > 1) {
        groupIdSymbol = Optional.of(symbolAllocator.newSymbol("groupId", BIGINT));
        groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSets, groupingSetMappings, subPlan.getRoot().getOutputSymbols(), groupIdSymbol.get());
    } else {
        Assignments.Builder assignments = Assignments.builder();
        assignments.putIdentities(subPlan.getRoot().getOutputSymbols());
        groupingSetMappings.forEach((key, value) -> assignments.put(key, value.toSymbolReference()));
        groupId = new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), assignments.build());
    }
    subPlan = new PlanBuilder(subPlan.getTranslations().withNewMappings(complexExpressions, Arrays.asList(fields)), groupId);
    return new GroupingSetsPlan(subPlan, columnOnlyGroupingSets, groupingSets, groupIdSymbol);
}
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) 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) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Assignments(io.trino.sql.planner.plan.Assignments) PlanBuilder.newPlanBuilder(io.trino.sql.planner.PlanBuilder.newPlanBuilder) LinkedHashMap(java.util.LinkedHashMap) PlanNode(io.trino.sql.planner.plan.PlanNode) 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) GroupIdNode(io.trino.sql.planner.plan.GroupIdNode) FieldId(io.trino.sql.analyzer.FieldId) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ProjectNode(io.trino.sql.planner.plan.ProjectNode)

Example 2 with Node

use of io.trino.sql.tree.Node 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 3 with Node

use of io.trino.sql.tree.Node 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 4 with Node

use of io.trino.sql.tree.Node in project trino by trinodb.

the class AstBuilder method visitQueryNoWith.

@Override
public Node visitQueryNoWith(SqlBaseParser.QueryNoWithContext context) {
    QueryBody term = (QueryBody) visit(context.queryTerm());
    Optional<OrderBy> orderBy = Optional.empty();
    if (context.ORDER() != null) {
        orderBy = Optional.of(new OrderBy(getLocation(context.ORDER()), visit(context.sortItem(), SortItem.class)));
    }
    Optional<Offset> offset = Optional.empty();
    if (context.OFFSET() != null) {
        Expression rowCount;
        if (context.offset.INTEGER_VALUE() != null) {
            rowCount = new LongLiteral(getLocation(context.offset.INTEGER_VALUE()), context.offset.getText());
        } else {
            rowCount = new Parameter(getLocation(context.offset.QUESTION_MARK()), parameterPosition);
            parameterPosition++;
        }
        offset = Optional.of(new Offset(Optional.of(getLocation(context.OFFSET())), rowCount));
    }
    Optional<Node> limit = Optional.empty();
    if (context.FETCH() != null) {
        Optional<Expression> rowCount = Optional.empty();
        if (context.fetchFirst != null) {
            if (context.fetchFirst.INTEGER_VALUE() != null) {
                rowCount = Optional.of(new LongLiteral(getLocation(context.fetchFirst.INTEGER_VALUE()), context.fetchFirst.getText()));
            } else {
                rowCount = Optional.of(new Parameter(getLocation(context.fetchFirst.QUESTION_MARK()), parameterPosition));
                parameterPosition++;
            }
        }
        limit = Optional.of(new FetchFirst(Optional.of(getLocation(context.FETCH())), rowCount, context.TIES() != null));
    } else if (context.LIMIT() != null) {
        if (context.limit == null) {
            throw new IllegalStateException("Missing LIMIT value");
        }
        Expression rowCount;
        if (context.limit.ALL() != null) {
            rowCount = new AllRows(getLocation(context.limit.ALL()));
        } else if (context.limit.rowCount().INTEGER_VALUE() != null) {
            rowCount = new LongLiteral(getLocation(context.limit.rowCount().INTEGER_VALUE()), context.limit.getText());
        } else {
            rowCount = new Parameter(getLocation(context.limit.rowCount().QUESTION_MARK()), parameterPosition);
            parameterPosition++;
        }
        limit = Optional.of(new Limit(Optional.of(getLocation(context.LIMIT())), rowCount));
    }
    if (term instanceof QuerySpecification) {
        // When we have a simple query specification
        // followed by order by, offset, limit or fetch,
        // fold the order by, limit, offset or fetch clauses
        // into the query specification (analyzer/planner
        // expects this structure to resolve references with respect
        // to columns defined in the query specification)
        QuerySpecification query = (QuerySpecification) term;
        return new Query(getLocation(context), Optional.empty(), new QuerySpecification(getLocation(context), query.getSelect(), query.getFrom(), query.getWhere(), query.getGroupBy(), query.getHaving(), query.getWindows(), orderBy, offset, limit), Optional.empty(), Optional.empty(), Optional.empty());
    }
    return new Query(getLocation(context), Optional.empty(), term, orderBy, offset, limit);
}
Also used : OrderBy(io.trino.sql.tree.OrderBy) AllRows(io.trino.sql.tree.AllRows) Query(io.trino.sql.tree.Query) WithQuery(io.trino.sql.tree.WithQuery) LongLiteral(io.trino.sql.tree.LongLiteral) Node(io.trino.sql.tree.Node) TerminalNode(org.antlr.v4.runtime.tree.TerminalNode) Offset(io.trino.sql.tree.Offset) QuerySpecification(io.trino.sql.tree.QuerySpecification) SortItem(io.trino.sql.tree.SortItem) DereferenceExpression(io.trino.sql.tree.DereferenceExpression) LogicalExpression(io.trino.sql.tree.LogicalExpression) SearchedCaseExpression(io.trino.sql.tree.SearchedCaseExpression) BindExpression(io.trino.sql.tree.BindExpression) CoalesceExpression(io.trino.sql.tree.CoalesceExpression) QuantifiedComparisonExpression(io.trino.sql.tree.QuantifiedComparisonExpression) SimpleCaseExpression(io.trino.sql.tree.SimpleCaseExpression) SubqueryExpression(io.trino.sql.tree.SubqueryExpression) LambdaExpression(io.trino.sql.tree.LambdaExpression) SubscriptExpression(io.trino.sql.tree.SubscriptExpression) NullIfExpression(io.trino.sql.tree.NullIfExpression) ArithmeticUnaryExpression(io.trino.sql.tree.ArithmeticUnaryExpression) InListExpression(io.trino.sql.tree.InListExpression) NotExpression(io.trino.sql.tree.NotExpression) ArithmeticBinaryExpression(io.trino.sql.tree.ArithmeticBinaryExpression) TryExpression(io.trino.sql.tree.TryExpression) ComparisonExpression(io.trino.sql.tree.ComparisonExpression) IfExpression(io.trino.sql.tree.IfExpression) Expression(io.trino.sql.tree.Expression) NumericParameter(io.trino.sql.tree.NumericParameter) DataTypeParameter(io.trino.sql.tree.DataTypeParameter) TypeParameter(io.trino.sql.tree.TypeParameter) Parameter(io.trino.sql.tree.Parameter) Limit(io.trino.sql.tree.Limit) QueryBody(io.trino.sql.tree.QueryBody) FetchFirst(io.trino.sql.tree.FetchFirst)

Example 5 with Node

use of io.trino.sql.tree.Node in project trino by trinodb.

the class AstUtils method treeHash.

/**
 * <p>Computes a hash of the given AST by applying the provided subtree hasher at each level.</p>
 *
 * <p>If the hasher returns a non-empty {@link OptionalInt}, the value is treated as the hash for
 * the subtree at that node. Otherwise, the hashes of its children are computed and combined.</p>
 */
public static int treeHash(Node node, Function<Node, OptionalInt> subtreeHasher) {
    OptionalInt hash = subtreeHasher.apply(node);
    if (hash.isPresent()) {
        return hash.getAsInt();
    }
    List<? extends Node> children = node.getChildren();
    int result = node.getClass().hashCode();
    for (Node element : children) {
        result = 31 * result + treeHash(element, subtreeHasher);
    }
    return result;
}
Also used : Node(io.trino.sql.tree.Node) OptionalInt(java.util.OptionalInt)

Aggregations

Node (io.trino.sql.tree.Node)8 ComparisonExpression (io.trino.sql.tree.ComparisonExpression)7 Expression (io.trino.sql.tree.Expression)7 Query (io.trino.sql.tree.Query)7 QuerySpecification (io.trino.sql.tree.QuerySpecification)7 SortItem (io.trino.sql.tree.SortItem)7 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)5 ImmutableList (com.google.common.collect.ImmutableList)5 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)5 ImmutableListMultimap (com.google.common.collect.ImmutableListMultimap)5 ImmutableMap (com.google.common.collect.ImmutableMap)5 ImmutableMap.toImmutableMap (com.google.common.collect.ImmutableMap.toImmutableMap)5 ImmutableSet (com.google.common.collect.ImmutableSet)5 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)5 Iterables.getOnlyElement (com.google.common.collect.Iterables.getOnlyElement)5 Session (io.trino.Session)5 TableHandle (io.trino.metadata.TableHandle)5 ColumnHandle (io.trino.spi.connector.ColumnHandle)5 Type (io.trino.spi.type.Type)5 NodeUtils.getSortItemsFromOrderBy (io.trino.sql.NodeUtils.getSortItemsFromOrderBy)5