Search in sources :

Example 1 with LambdaArgumentDeclaration

use of io.trino.sql.tree.LambdaArgumentDeclaration 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 LambdaArgumentDeclaration

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

the class LogicalPlanner method buildLambdaDeclarationToSymbolMap.

private static Map<NodeRef<LambdaArgumentDeclaration>, Symbol> buildLambdaDeclarationToSymbolMap(Analysis analysis, SymbolAllocator symbolAllocator) {
    Map<Key, Symbol> allocations = new HashMap<>();
    Map<NodeRef<LambdaArgumentDeclaration>, Symbol> result = new LinkedHashMap<>();
    for (Entry<NodeRef<Expression>, Type> entry : analysis.getTypes().entrySet()) {
        if (!(entry.getKey().getNode() instanceof LambdaArgumentDeclaration)) {
            continue;
        }
        LambdaArgumentDeclaration argument = (LambdaArgumentDeclaration) entry.getKey().getNode();
        Key key = new Key(argument, entry.getValue());
        // Allocate the same symbol for all lambda argument names with a given type. This is needed to be able to
        // properly identify multiple instances of syntactically equal lambda expressions during planning as expressions
        // get rewritten via TranslationMap
        Symbol symbol = allocations.get(key);
        if (symbol == null) {
            symbol = symbolAllocator.newSymbol(argument, entry.getValue());
            allocations.put(key, symbol);
        }
        result.put(NodeRef.of(argument), symbol);
    }
    return result;
}
Also used : NodeRef(io.trino.sql.tree.NodeRef) 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) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 3 with LambdaArgumentDeclaration

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

the class AstBuilder method visitLambda.

@Override
public Node visitLambda(SqlBaseParser.LambdaContext context) {
    List<LambdaArgumentDeclaration> arguments = visit(context.identifier(), Identifier.class).stream().map(LambdaArgumentDeclaration::new).collect(toList());
    Expression body = (Expression) visit(context.expression());
    return new LambdaExpression(getLocation(context), arguments, body);
}
Also used : LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) Identifier(io.trino.sql.tree.Identifier) 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) LambdaExpression(io.trino.sql.tree.LambdaExpression)

Example 4 with LambdaArgumentDeclaration

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

the class TestSqlParser method testLambda.

@Test
public void testLambda() {
    assertExpression("() -> x", new LambdaExpression(ImmutableList.of(), new Identifier("x")));
    assertExpression("x -> sin(x)", new LambdaExpression(ImmutableList.of(new LambdaArgumentDeclaration(identifier("x"))), new FunctionCall(QualifiedName.of("sin"), ImmutableList.of(new Identifier("x")))));
    assertExpression("(x, y) -> mod(x, y)", new LambdaExpression(ImmutableList.of(new LambdaArgumentDeclaration(identifier("x")), new LambdaArgumentDeclaration(identifier("y"))), new FunctionCall(QualifiedName.of("mod"), ImmutableList.of(new Identifier("x"), new Identifier("y")))));
}
Also used : QueryUtil.quotedIdentifier(io.trino.sql.QueryUtil.quotedIdentifier) Identifier(io.trino.sql.tree.Identifier) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) FunctionCall(io.trino.sql.tree.FunctionCall) LambdaExpression(io.trino.sql.tree.LambdaExpression) Test(org.junit.jupiter.api.Test)

Example 5 with LambdaArgumentDeclaration

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

the class TestLambdaCaptureDesugaringRewriter method testRewriteBasicLambda.

@Test
public void testRewriteBasicLambda() {
    Map<Symbol, Type> symbols = ImmutableMap.of(new Symbol("a"), BigintType.BIGINT);
    SymbolAllocator allocator = new SymbolAllocator(symbols);
    assertEquals(rewrite(expression("x -> a + x"), allocator.getTypes(), allocator), new BindExpression(ImmutableList.of(expression("a")), new LambdaExpression(Stream.of("a_0", "x").map(Identifier::new).map(LambdaArgumentDeclaration::new).collect(toList()), expression("a_0 + x"))));
}
Also used : SymbolAllocator(io.trino.sql.planner.SymbolAllocator) Type(io.trino.spi.type.Type) BigintType(io.trino.spi.type.BigintType) LambdaArgumentDeclaration(io.trino.sql.tree.LambdaArgumentDeclaration) Symbol(io.trino.sql.planner.Symbol) BindExpression(io.trino.sql.tree.BindExpression) LambdaExpression(io.trino.sql.tree.LambdaExpression) Test(org.testng.annotations.Test)

Aggregations

LambdaArgumentDeclaration (io.trino.sql.tree.LambdaArgumentDeclaration)5 Type (io.trino.spi.type.Type)3 LambdaExpression (io.trino.sql.tree.LambdaExpression)3 CharType (io.trino.spi.type.CharType)2 VarcharType (io.trino.spi.type.VarcharType)2 RelationType (io.trino.sql.analyzer.RelationType)2 TypeSignatureTranslator.toSqlType (io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType)2 CoalesceExpression (io.trino.sql.tree.CoalesceExpression)2 ComparisonExpression (io.trino.sql.tree.ComparisonExpression)2 Expression (io.trino.sql.tree.Expression)2 FunctionCall (io.trino.sql.tree.FunctionCall)2 Identifier (io.trino.sql.tree.Identifier)2 IfExpression (io.trino.sql.tree.IfExpression)2 NodeRef (io.trino.sql.tree.NodeRef)2 UnknownType (io.trino.type.UnknownType)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 Verify.verify (com.google.common.base.Verify.verify)1 ImmutableList (com.google.common.collect.ImmutableList)1