Search in sources :

Example 26 with SqlParser

use of com.facebook.presto.sql.parser.SqlParser in project presto by prestodb.

the class CreateViewTask method execute.

@Override
public ListenableFuture<?> execute(CreateView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) {
    Session session = stateMachine.getSession();
    QualifiedObjectName name = createQualifiedObjectName(session, statement, statement.getName());
    accessControl.checkCanCreateView(session.getRequiredTransactionId(), session.getIdentity(), name);
    String sql = getFormattedSql(statement.getQuery(), sqlParser, Optional.of(parameters));
    Analysis analysis = analyzeStatement(statement, session, metadata, accessControl, parameters);
    List<ViewColumn> columns = analysis.getOutputDescriptor(statement.getQuery()).getVisibleFields().stream().map(field -> new ViewColumn(field.getName().get(), field.getType())).collect(toImmutableList());
    String data = codec.toJson(new ViewDefinition(sql, session.getCatalog(), session.getSchema(), columns, Optional.of(session.getUser())));
    metadata.createView(session, name, data, statement.isReplace());
    return immediateFuture(null);
}
Also used : QualifiedObjectName(com.facebook.presto.metadata.QualifiedObjectName) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) Analyzer(com.facebook.presto.sql.analyzer.Analyzer) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ViewDefinition(com.facebook.presto.metadata.ViewDefinition) Session(com.facebook.presto.Session) SqlParser(com.facebook.presto.sql.parser.SqlParser) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) Inject(javax.inject.Inject) SqlFormatterUtil.getFormattedSql(com.facebook.presto.sql.SqlFormatterUtil.getFormattedSql) List(java.util.List) Expression(com.facebook.presto.sql.tree.Expression) MetadataUtil.createQualifiedObjectName(com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName) ViewColumn(com.facebook.presto.metadata.ViewDefinition.ViewColumn) Objects.requireNonNull(java.util.Objects.requireNonNull) Analysis(com.facebook.presto.sql.analyzer.Analysis) Optional(java.util.Optional) ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) TransactionManager(com.facebook.presto.transaction.TransactionManager) Metadata(com.facebook.presto.metadata.Metadata) AccessControl(com.facebook.presto.security.AccessControl) CreateView(com.facebook.presto.sql.tree.CreateView) Statement(com.facebook.presto.sql.tree.Statement) JsonCodec(io.airlift.json.JsonCodec) Analysis(com.facebook.presto.sql.analyzer.Analysis) ViewColumn(com.facebook.presto.metadata.ViewDefinition.ViewColumn) ViewDefinition(com.facebook.presto.metadata.ViewDefinition) QualifiedObjectName(com.facebook.presto.metadata.QualifiedObjectName) MetadataUtil.createQualifiedObjectName(com.facebook.presto.metadata.MetadataUtil.createQualifiedObjectName) Session(com.facebook.presto.Session)

Example 27 with SqlParser

use of com.facebook.presto.sql.parser.SqlParser in project presto by prestodb.

the class TestCostCalculator method setUp.

@BeforeClass
public void setUp() {
    TaskCountEstimator taskCountEstimator = new TaskCountEstimator(() -> NUMBER_OF_NODES);
    costCalculatorUsingExchanges = new CostCalculatorUsingExchanges(taskCountEstimator);
    costCalculatorWithEstimatedExchanges = new CostCalculatorWithEstimatedExchanges(costCalculatorUsingExchanges, taskCountEstimator);
    session = testSessionBuilder().setCatalog("tpch").build();
    CatalogManager catalogManager = new CatalogManager();
    catalogManager.registerCatalog(createBogusTestingCatalog("tpch"));
    transactionManager = createTestTransactionManager(catalogManager);
    metadata = createTestMetadataManager(transactionManager, new FeaturesConfig());
    finalizerService = new FinalizerService();
    finalizerService.start();
    nodeScheduler = new NodeScheduler(new LegacyNetworkTopology(), new InMemoryNodeManager(), new NodeSelectionStats(), new NodeSchedulerConfig().setIncludeCoordinator(true), new NodeTaskMap(finalizerService), new ThrowingNodeTtlFetcherManager(), new NoOpQueryManager(), new SimpleTtlNodeSelectorConfig());
    PartitioningProviderManager partitioningProviderManager = new PartitioningProviderManager();
    nodePartitioningManager = new NodePartitioningManager(nodeScheduler, partitioningProviderManager, new NodeSelectionStats());
    planFragmenter = new PlanFragmenter(metadata, nodePartitioningManager, new QueryManagerConfig(), new SqlParser(), new FeaturesConfig());
}
Also used : NodeTaskMap(com.facebook.presto.execution.NodeTaskMap) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) PartitioningProviderManager(com.facebook.presto.sql.planner.PartitioningProviderManager) SqlParser(com.facebook.presto.sql.parser.SqlParser) NodeSchedulerConfig(com.facebook.presto.execution.scheduler.NodeSchedulerConfig) PlanFragmenter(com.facebook.presto.sql.planner.PlanFragmenter) ThrowingNodeTtlFetcherManager(com.facebook.presto.ttl.nodettlfetchermanagers.ThrowingNodeTtlFetcherManager) CatalogManager(com.facebook.presto.metadata.CatalogManager) NodePartitioningManager(com.facebook.presto.sql.planner.NodePartitioningManager) InMemoryNodeManager(com.facebook.presto.metadata.InMemoryNodeManager) NoOpQueryManager(com.facebook.presto.dispatcher.NoOpQueryManager) NodeSelectionStats(com.facebook.presto.execution.scheduler.nodeSelection.NodeSelectionStats) FinalizerService(com.facebook.presto.util.FinalizerService) LegacyNetworkTopology(com.facebook.presto.execution.scheduler.LegacyNetworkTopology) NodeScheduler(com.facebook.presto.execution.scheduler.NodeScheduler) QueryManagerConfig(com.facebook.presto.execution.QueryManagerConfig) SimpleTtlNodeSelectorConfig(com.facebook.presto.execution.scheduler.nodeSelection.SimpleTtlNodeSelectorConfig) BeforeClass(org.testng.annotations.BeforeClass)

Example 28 with SqlParser

use of com.facebook.presto.sql.parser.SqlParser in project presto by prestodb.

the class TestWindowNode method getJsonCodec.

private JsonCodec<WindowNode> getJsonCodec() throws Exception {
    Module module = binder -> {
        SqlParser sqlParser = new SqlParser();
        FunctionAndTypeManager functionAndTypeManager = createTestFunctionAndTypeManager();
        binder.install(new JsonModule());
        binder.install(new HandleJsonModule());
        binder.bind(SqlParser.class).toInstance(sqlParser);
        binder.bind(TypeManager.class).toInstance(functionAndTypeManager);
        configBinder(binder).bindConfig(FeaturesConfig.class);
        newSetBinder(binder, Type.class);
        jsonBinder(binder).addSerializerBinding(Slice.class).to(SliceSerializer.class);
        jsonBinder(binder).addDeserializerBinding(Slice.class).to(SliceDeserializer.class);
        jsonBinder(binder).addDeserializerBinding(Type.class).to(TypeDeserializer.class);
        jsonBinder(binder).addSerializerBinding(Expression.class).to(Serialization.ExpressionSerializer.class);
        jsonBinder(binder).addDeserializerBinding(Expression.class).to(Serialization.ExpressionDeserializer.class);
        jsonBinder(binder).addDeserializerBinding(FunctionCall.class).to(Serialization.FunctionCallDeserializer.class);
        jsonBinder(binder).addKeySerializerBinding(VariableReferenceExpression.class).to(Serialization.VariableReferenceExpressionSerializer.class);
        jsonBinder(binder).addKeyDeserializerBinding(VariableReferenceExpression.class).to(Serialization.VariableReferenceExpressionDeserializer.class);
        jsonCodecBinder(binder).bindJsonCodec(WindowNode.class);
    };
    Bootstrap app = new Bootstrap(ImmutableList.of(module));
    Injector injector = app.doNotInitializeLogging().quiet().initialize();
    return injector.getInstance(new Key<JsonCodec<WindowNode>>() {
    });
}
Also used : FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) Module(com.google.inject.Module) JsonCodec(com.facebook.airlift.json.JsonCodec) SliceSerializer(com.facebook.presto.server.SliceSerializer) Key(com.google.inject.Key) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) Test(org.testng.annotations.Test) ValuesNode(com.facebook.presto.spi.plan.ValuesNode) Map(java.util.Map) HandleJsonModule(com.facebook.presto.metadata.HandleJsonModule) Multibinder.newSetBinder(com.google.inject.multibindings.Multibinder.newSetBinder) CallExpression(com.facebook.presto.spi.relation.CallExpression) OrderingScheme(com.facebook.presto.spi.plan.OrderingScheme) JsonModule(com.facebook.airlift.json.JsonModule) FunctionCall(com.facebook.presto.sql.tree.FunctionCall) ImmutableSet(com.google.common.collect.ImmutableSet) SortOrder(com.facebook.presto.common.block.SortOrder) ImmutableMap(com.google.common.collect.ImmutableMap) Ordering(com.facebook.presto.spi.plan.Ordering) BeforeClass(org.testng.annotations.BeforeClass) Set(java.util.Set) JsonBinder.jsonBinder(com.facebook.airlift.json.JsonBinder.jsonBinder) UUID(java.util.UUID) SqlParser(com.facebook.presto.sql.parser.SqlParser) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) PlanVariableAllocator(com.facebook.presto.sql.planner.PlanVariableAllocator) Optional(java.util.Optional) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) Bootstrap(com.facebook.airlift.bootstrap.Bootstrap) Slice(io.airlift.slice.Slice) Assert.assertEquals(org.testng.Assert.assertEquals) FunctionAndTypeManager.createTestFunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager) TypeSignatureProvider.fromTypes(com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes) Expressions.call(com.facebook.presto.sql.relational.Expressions.call) JsonCodecBinder.jsonCodecBinder(com.facebook.airlift.json.JsonCodecBinder.jsonCodecBinder) RANGE(com.facebook.presto.sql.planner.plan.WindowNode.Frame.WindowType.RANGE) Serialization(com.facebook.presto.sql.Serialization) SliceDeserializer(com.facebook.presto.server.SliceDeserializer) ImmutableList(com.google.common.collect.ImmutableList) TypeManager(com.facebook.presto.common.type.TypeManager) UNBOUNDED_PRECEDING(com.facebook.presto.sql.planner.plan.WindowNode.Frame.BoundType.UNBOUNDED_PRECEDING) UNBOUNDED_FOLLOWING(com.facebook.presto.sql.planner.plan.WindowNode.Frame.BoundType.UNBOUNDED_FOLLOWING) Type(com.facebook.presto.common.type.Type) BIGINT(com.facebook.presto.common.type.BigintType.BIGINT) Injector(com.google.inject.Injector) TypeDeserializer(com.facebook.presto.type.TypeDeserializer) Expression(com.facebook.presto.sql.tree.Expression) MetadataManager.createTestMetadataManager(com.facebook.presto.metadata.MetadataManager.createTestMetadataManager) FunctionHandle(com.facebook.presto.spi.function.FunctionHandle) ConfigBinder.configBinder(com.facebook.airlift.configuration.ConfigBinder.configBinder) FeaturesConfig(com.facebook.presto.sql.analyzer.FeaturesConfig) SqlParser(com.facebook.presto.sql.parser.SqlParser) SliceSerializer(com.facebook.presto.server.SliceSerializer) HandleJsonModule(com.facebook.presto.metadata.HandleJsonModule) JsonModule(com.facebook.airlift.json.JsonModule) Type(com.facebook.presto.common.type.Type) SliceDeserializer(com.facebook.presto.server.SliceDeserializer) JsonCodec(com.facebook.airlift.json.JsonCodec) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) FunctionAndTypeManager.createTestFunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager) HandleJsonModule(com.facebook.presto.metadata.HandleJsonModule) Injector(com.google.inject.Injector) Bootstrap(com.facebook.airlift.bootstrap.Bootstrap) Module(com.google.inject.Module) HandleJsonModule(com.facebook.presto.metadata.HandleJsonModule) JsonModule(com.facebook.airlift.json.JsonModule) TypeDeserializer(com.facebook.presto.type.TypeDeserializer)

Example 29 with SqlParser

use of com.facebook.presto.sql.parser.SqlParser in project presto by prestodb.

the class PropertyDerivations method deriveProperties.

public static ActualProperties deriveProperties(PlanNode node, List<ActualProperties> inputProperties, Metadata metadata, Session session, TypeProvider types, SqlParser parser) {
    ActualProperties output = node.accept(new Visitor(metadata, session, types, parser), inputProperties);
    output.getNodePartitioning().ifPresent(partitioning -> verify(node.getOutputVariables().containsAll(partitioning.getVariableReferences()), "Node-level partitioning properties contain columns not present in node's output"));
    verify(node.getOutputVariables().containsAll(output.getConstants().keySet()), "Node-level constant properties contain columns not present in node's output");
    Set<VariableReferenceExpression> localPropertyColumns = output.getLocalProperties().stream().flatMap(property -> property.getColumns().stream()).collect(Collectors.toSet());
    verify(node.getOutputVariables().containsAll(localPropertyColumns), "Node-level local properties contain columns not present in node's output");
    return output;
}
Also used : AggregationNode(com.facebook.presto.spi.plan.AggregationNode) ExplainAnalyzeNode(com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode) RowExpressionDomainTranslator(com.facebook.presto.sql.relational.RowExpressionDomainTranslator) SpatialJoinNode(com.facebook.presto.sql.planner.plan.SpatialJoinNode) SortNode(com.facebook.presto.sql.planner.plan.SortNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) TableWriterNode(com.facebook.presto.sql.planner.plan.TableWriterNode) ValuesNode(com.facebook.presto.spi.plan.ValuesNode) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Collectors.toMap(java.util.stream.Collectors.toMap) TypeProvider(com.facebook.presto.sql.planner.TypeProvider) TopNRowNumberNode(com.facebook.presto.sql.planner.plan.TopNRowNumberNode) Map(java.util.Map) LocalProperty(com.facebook.presto.spi.LocalProperty) IndexSourceNode(com.facebook.presto.sql.planner.plan.IndexSourceNode) Global.singleStreamPartition(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.singleStreamPartition) IndexJoinNode(com.facebook.presto.sql.planner.plan.IndexJoinNode) OrderingScheme(com.facebook.presto.spi.plan.OrderingScheme) OutputNode(com.facebook.presto.sql.planner.plan.OutputNode) RowExpressionInterpreter(com.facebook.presto.sql.planner.RowExpressionInterpreter) ImmutableSet(com.google.common.collect.ImmutableSet) LateralJoinNode(com.facebook.presto.sql.planner.plan.LateralJoinNode) RowNumberNode(com.facebook.presto.sql.planner.plan.RowNumberNode) ImmutableMap(com.google.common.collect.ImmutableMap) Global.arbitraryPartition(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.arbitraryPartition) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) TablePartitioning(com.facebook.presto.metadata.TableLayout.TablePartitioning) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) SqlParser(com.facebook.presto.sql.parser.SqlParser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) LimitNode(com.facebook.presto.spi.plan.LimitNode) SystemSessionProperties.isSpillEnabled(com.facebook.presto.SystemSessionProperties.isSpillEnabled) List(java.util.List) Global.streamPartitionedOn(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.streamPartitionedOn) ProjectNode(com.facebook.presto.spi.plan.ProjectNode) Global(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global) SampleNode(com.facebook.presto.sql.planner.plan.SampleNode) Optional(java.util.Optional) Global.coordinatorSingleStreamPartition(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.coordinatorSingleStreamPartition) ApplyNode(com.facebook.presto.sql.planner.plan.ApplyNode) AssignUniqueId(com.facebook.presto.sql.planner.plan.AssignUniqueId) TupleDomain.toLinkedMap(com.facebook.presto.common.predicate.TupleDomain.toLinkedMap) MarkDistinctNode(com.facebook.presto.spi.plan.MarkDistinctNode) ARBITRARY_DISTRIBUTION(com.facebook.presto.sql.planner.SystemPartitioningHandle.ARBITRARY_DISTRIBUTION) Iterables(com.google.common.collect.Iterables) Global.partitionedOn(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.partitionedOn) GroupIdNode(com.facebook.presto.sql.planner.plan.GroupIdNode) HashMap(java.util.HashMap) DistinctLimitNode(com.facebook.presto.spi.plan.DistinctLimitNode) ConstantExpression(com.facebook.presto.spi.relation.ConstantExpression) TableWriterMergeNode(com.facebook.presto.sql.planner.plan.TableWriterMergeNode) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) FilterNode(com.facebook.presto.spi.plan.FilterNode) ImmutableList(com.google.common.collect.ImmutableList) SortingProperty(com.facebook.presto.spi.SortingProperty) Verify.verify(com.google.common.base.Verify.verify) BASIC_COLUMN_EXTRACTOR(com.facebook.presto.spi.relation.DomainTranslator.BASIC_COLUMN_EXTRACTOR) SystemSessionProperties.isJoinSpillingEnabled(com.facebook.presto.SystemSessionProperties.isJoinSpillingEnabled) InternalPlanVisitor(com.facebook.presto.sql.planner.plan.InternalPlanVisitor) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) UnnestNode(com.facebook.presto.sql.planner.plan.UnnestNode) RowExpression(com.facebook.presto.spi.relation.RowExpression) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) TableLayout(com.facebook.presto.metadata.TableLayout) WindowNode(com.facebook.presto.sql.planner.plan.WindowNode) Session(com.facebook.presto.Session) GroupingProperty(com.facebook.presto.spi.GroupingProperty) ConstantProperty(com.facebook.presto.spi.ConstantProperty) SystemSessionProperties.planWithTableNodePartitioning(com.facebook.presto.SystemSessionProperties.planWithTableNodePartitioning) TupleDomain(com.facebook.presto.common.predicate.TupleDomain) DeleteNode(com.facebook.presto.sql.planner.plan.DeleteNode) OPTIMIZED(com.facebook.presto.spi.relation.ExpressionOptimizer.Level.OPTIMIZED) PlanNode(com.facebook.presto.spi.plan.PlanNode) ColumnHandle(com.facebook.presto.spi.ColumnHandle) TableScanNode(com.facebook.presto.spi.plan.TableScanNode) SemiJoinNode(com.facebook.presto.sql.planner.plan.SemiJoinNode) TopNNode(com.facebook.presto.spi.plan.TopNNode) PartitioningHandle(com.facebook.presto.sql.planner.PartitioningHandle) TableFinishNode(com.facebook.presto.sql.planner.plan.TableFinishNode) Metadata(com.facebook.presto.metadata.Metadata) EnforceSingleRowNode(com.facebook.presto.sql.planner.plan.EnforceSingleRowNode) ExchangeNode(com.facebook.presto.sql.planner.plan.ExchangeNode) StatisticsWriterNode(com.facebook.presto.sql.planner.plan.StatisticsWriterNode) Global.partitionedOnCoalesce(com.facebook.presto.sql.planner.optimizations.ActualProperties.Global.partitionedOnCoalesce) InternalPlanVisitor(com.facebook.presto.sql.planner.plan.InternalPlanVisitor) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression)

Example 30 with SqlParser

use of com.facebook.presto.sql.parser.SqlParser in project presto by prestodb.

the class TranslateExpressions method createRewriter.

private static PlanRowExpressionRewriter createRewriter(Metadata metadata, SqlParser sqlParser) {
    return new PlanRowExpressionRewriter() {

        @Override
        public RowExpression rewrite(RowExpression expression, Rule.Context context) {
            // special treatment of the CallExpression in Aggregation
            if (expression instanceof CallExpression && ((CallExpression) expression).getArguments().stream().anyMatch(OriginalExpressionUtils::isExpression)) {
                return removeOriginalExpressionArguments((CallExpression) expression, context.getSession(), context.getVariableAllocator());
            }
            return removeOriginalExpression(expression, context);
        }

        private RowExpression removeOriginalExpressionArguments(CallExpression callExpression, Session session, PlanVariableAllocator variableAllocator) {
            Map<NodeRef<Expression>, Type> types = analyzeCallExpressionTypes(callExpression, session, variableAllocator.getTypes());
            return new CallExpression(callExpression.getSourceLocation(), callExpression.getDisplayName(), callExpression.getFunctionHandle(), callExpression.getType(), callExpression.getArguments().stream().map(expression -> removeOriginalExpression(expression, session, types)).collect(toImmutableList()));
        }

        private Map<NodeRef<Expression>, Type> analyzeCallExpressionTypes(CallExpression callExpression, Session session, TypeProvider typeProvider) {
            List<LambdaExpression> lambdaExpressions = callExpression.getArguments().stream().filter(OriginalExpressionUtils::isExpression).map(OriginalExpressionUtils::castToExpression).filter(LambdaExpression.class::isInstance).map(LambdaExpression.class::cast).collect(toImmutableList());
            ImmutableMap.Builder<NodeRef<Expression>, Type> builder = ImmutableMap.<NodeRef<Expression>, Type>builder();
            if (!lambdaExpressions.isEmpty()) {
                List<FunctionType> functionTypes = metadata.getFunctionAndTypeManager().getFunctionMetadata(callExpression.getFunctionHandle()).getArgumentTypes().stream().filter(typeSignature -> typeSignature.getBase().equals(FunctionType.NAME)).map(typeSignature -> (FunctionType) (metadata.getFunctionAndTypeManager().getType(typeSignature))).collect(toImmutableList());
                InternalAggregationFunction internalAggregationFunction = metadata.getFunctionAndTypeManager().getAggregateFunctionImplementation(callExpression.getFunctionHandle());
                List<Class> lambdaInterfaces = internalAggregationFunction.getLambdaInterfaces();
                verify(lambdaExpressions.size() == functionTypes.size());
                verify(lambdaExpressions.size() == lambdaInterfaces.size());
                for (int i = 0; i < lambdaExpressions.size(); i++) {
                    LambdaExpression lambdaExpression = lambdaExpressions.get(i);
                    FunctionType functionType = functionTypes.get(i);
                    // To compile lambda, LambdaDefinitionExpression needs to be generated from LambdaExpression,
                    // which requires the types of all sub-expressions.
                    // 
                    // In project and filter expression compilation, ExpressionAnalyzer.getExpressionTypesFromInput
                    // is used to generate the types of all sub-expressions. (see visitScanFilterAndProject and visitFilter)
                    // 
                    // This does not work here since the function call representation in final aggregation node
                    // is currently a hack: it takes intermediate type as input, and may not be a valid
                    // function call in Presto.
                    // 
                    // TODO: Once the final aggregation function call representation is fixed,
                    // the same mechanism in project and filter expression should be used here.
                    verify(lambdaExpression.getArguments().size() == functionType.getArgumentTypes().size());
                    Map<NodeRef<Expression>, Type> lambdaArgumentExpressionTypes = new HashMap<>();
                    Map<String, Type> lambdaArgumentSymbolTypes = new HashMap<>();
                    for (int j = 0; j < lambdaExpression.getArguments().size(); j++) {
                        LambdaArgumentDeclaration argument = lambdaExpression.getArguments().get(j);
                        Type type = functionType.getArgumentTypes().get(j);
                        lambdaArgumentExpressionTypes.put(NodeRef.of(argument), type);
                        lambdaArgumentSymbolTypes.put(argument.getName().getValue(), type);
                    }
                    // the lambda expression itself
                    builder.put(NodeRef.of(lambdaExpression), functionType).putAll(lambdaArgumentExpressionTypes).putAll(getExpressionTypes(session, metadata, sqlParser, TypeProvider.copyOf(lambdaArgumentSymbolTypes), lambdaExpression.getBody(), emptyList(), NOOP));
                }
            }
            for (RowExpression argument : callExpression.getArguments()) {
                if (!isExpression(argument) || castToExpression(argument) instanceof LambdaExpression) {
                    continue;
                }
                builder.putAll(analyze(castToExpression(argument), session, typeProvider));
            }
            return builder.build();
        }

        private Map<NodeRef<Expression>, Type> analyze(Expression expression, Session session, TypeProvider typeProvider) {
            return getExpressionTypes(session, metadata, sqlParser, typeProvider, expression, emptyList(), NOOP);
        }

        private RowExpression toRowExpression(Expression expression, Session session, Map<NodeRef<Expression>, Type> types) {
            return SqlToRowExpressionTranslator.translate(expression, types, ImmutableMap.of(), metadata.getFunctionAndTypeManager(), session);
        }

        private RowExpression removeOriginalExpression(RowExpression expression, Rule.Context context) {
            if (isExpression(expression)) {
                return toRowExpression(castToExpression(expression), context.getSession(), analyze(castToExpression(expression), context.getSession(), context.getVariableAllocator().getTypes()));
            }
            return expression;
        }

        private RowExpression removeOriginalExpression(RowExpression rowExpression, Session session, Map<NodeRef<Expression>, Type> types) {
            if (isExpression(rowExpression)) {
                Expression expression = castToExpression(rowExpression);
                return toRowExpression(expression, session, types);
            }
            return rowExpression;
        }
    };
}
Also used : LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) OriginalExpressionUtils(com.facebook.presto.sql.relational.OriginalExpressionUtils) SqlToRowExpressionTranslator(com.facebook.presto.sql.relational.SqlToRowExpressionTranslator) OriginalExpressionUtils.isExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.isExpression) HashMap(java.util.HashMap) OriginalExpressionUtils.castToExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToExpression) Verify.verify(com.google.common.base.Verify.verify) TypeProvider(com.facebook.presto.sql.planner.TypeProvider) Map(java.util.Map) CallExpression(com.facebook.presto.spi.relation.CallExpression) Type(com.facebook.presto.common.type.Type) RowExpression(com.facebook.presto.spi.relation.RowExpression) ImmutableMap(com.google.common.collect.ImmutableMap) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) Collections.emptyList(java.util.Collections.emptyList) Session(com.facebook.presto.Session) Rule(com.facebook.presto.sql.planner.iterative.Rule) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) InternalAggregationFunction(com.facebook.presto.operator.aggregation.InternalAggregationFunction) FunctionType(com.facebook.presto.common.type.FunctionType) SqlParser(com.facebook.presto.sql.parser.SqlParser) NodeRef(com.facebook.presto.sql.tree.NodeRef) List(java.util.List) Expression(com.facebook.presto.sql.tree.Expression) PlanVariableAllocator(com.facebook.presto.sql.planner.PlanVariableAllocator) NOOP(com.facebook.presto.spi.WarningCollector.NOOP) ExpressionAnalyzer.getExpressionTypes(com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes) Metadata(com.facebook.presto.metadata.Metadata) HashMap(java.util.HashMap) InternalAggregationFunction(com.facebook.presto.operator.aggregation.InternalAggregationFunction) NodeRef(com.facebook.presto.sql.tree.NodeRef) LambdaArgumentDeclaration(com.facebook.presto.sql.tree.LambdaArgumentDeclaration) PlanVariableAllocator(com.facebook.presto.sql.planner.PlanVariableAllocator) CallExpression(com.facebook.presto.spi.relation.CallExpression) FunctionType(com.facebook.presto.common.type.FunctionType) RowExpression(com.facebook.presto.spi.relation.RowExpression) TypeProvider(com.facebook.presto.sql.planner.TypeProvider) ImmutableMap(com.google.common.collect.ImmutableMap) Type(com.facebook.presto.common.type.Type) FunctionType(com.facebook.presto.common.type.FunctionType) OriginalExpressionUtils.isExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.isExpression) OriginalExpressionUtils.castToExpression(com.facebook.presto.sql.relational.OriginalExpressionUtils.castToExpression) CallExpression(com.facebook.presto.spi.relation.CallExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) Expression(com.facebook.presto.sql.tree.Expression) OriginalExpressionUtils(com.facebook.presto.sql.relational.OriginalExpressionUtils) LambdaExpression(com.facebook.presto.sql.tree.LambdaExpression) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Session(com.facebook.presto.Session)

Aggregations

SqlParser (com.facebook.presto.sql.parser.SqlParser)38 Expression (com.facebook.presto.sql.tree.Expression)11 Test (org.testng.annotations.Test)11 Metadata (com.facebook.presto.metadata.Metadata)10 Optional (java.util.Optional)10 WarningCollector (com.facebook.presto.spi.WarningCollector)8 RowExpression (com.facebook.presto.spi.relation.RowExpression)8 VariableReferenceExpression (com.facebook.presto.spi.relation.VariableReferenceExpression)8 TransactionManager (com.facebook.presto.transaction.TransactionManager)8 Session (com.facebook.presto.Session)7 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)7 List (java.util.List)7 Type (com.facebook.presto.common.type.Type)6 ImmutableList (com.google.common.collect.ImmutableList)6 AllowAllAccessControl (com.facebook.presto.security.AllowAllAccessControl)5 PlanVariableAllocator (com.facebook.presto.sql.planner.PlanVariableAllocator)5 Objects.requireNonNull (java.util.Objects.requireNonNull)5 TaskTestUtils.createQueryStateMachine (com.facebook.presto.execution.TaskTestUtils.createQueryStateMachine)4 PlanNode (com.facebook.presto.spi.plan.PlanNode)4 FeaturesConfig (com.facebook.presto.sql.analyzer.FeaturesConfig)4