Search in sources :

Example 26 with PlannerContext

use of io.crate.planner.PlannerContext in project crate by crate.

the class CollectTest method test.

@Test
public void test() throws Exception {
    var e = SQLExecutor.builder(clusterService).addTable("CREATE TABLE t (x int)").build();
    TableStats tableStats = new TableStats();
    PlannerContext plannerCtx = e.getPlannerContext(clusterService.state());
    ProjectionBuilder projectionBuilder = new ProjectionBuilder(e.nodeCtx);
    QueriedSelectRelation analyzedRelation = e.analyze("SELECT 123 AS alias, 456 AS alias2 FROM t ORDER BY alias, 2");
    LogicalPlanner logicalPlanner = new LogicalPlanner(e.nodeCtx, tableStats, () -> clusterService.state().nodes().getMinNodeVersion());
    LogicalPlan operator = logicalPlanner.plan(analyzedRelation, plannerCtx);
    ExecutionPlan build = operator.build(plannerCtx, Set.of(), projectionBuilder, -1, 0, null, null, Row.EMPTY, SubQueryResults.EMPTY);
    assertThat((((RoutedCollectPhase) ((io.crate.planner.node.dql.Collect) build).collectPhase())).orderBy(), is(nullValue()));
}
Also used : PlannerContext(io.crate.planner.PlannerContext) ExecutionPlan(io.crate.planner.ExecutionPlan) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) TableStats(io.crate.statistics.TableStats) ProjectionBuilder(io.crate.execution.dsl.projection.builder.ProjectionBuilder) RoutedCollectPhase(io.crate.execution.dsl.phases.RoutedCollectPhase) Test(org.junit.Test) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest)

Example 27 with PlannerContext

use of io.crate.planner.PlannerContext in project crate by crate.

the class Session method quickExec.

/**
 * Execute a query in one step, avoiding the parse/bind/execute/sync procedure.
 * Opposed to using parse/bind/execute/sync this method is thread-safe.
 *
 * @param parse A function to parse the statement; This can be used to cache the parsed statement.
 *              Use {@link #quickExec(String, ResultReceiver, Row)} to use the regular parser
 */
public void quickExec(String statement, Function<String, Statement> parse, ResultReceiver<?> resultReceiver, Row params) {
    CoordinatorTxnCtx txnCtx = new CoordinatorTxnCtx(sessionContext);
    Statement parsedStmt = parse.apply(statement);
    AnalyzedStatement analyzedStatement = analyzer.analyze(parsedStmt, sessionContext, ParamTypeHints.EMPTY);
    RoutingProvider routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    UUID jobId = UUIDs.dirtyUUID();
    ClusterState clusterState = planner.currentClusterState();
    PlannerContext plannerContext = new PlannerContext(clusterState, routingProvider, jobId, txnCtx, nodeCtx, 0, params);
    Plan plan;
    try {
        plan = planner.plan(analyzedStatement, plannerContext);
    } catch (Throwable t) {
        jobsLogs.logPreExecutionFailure(jobId, statement, SQLExceptions.messageOf(t), sessionContext.sessionUser());
        throw t;
    }
    StatementClassifier.Classification classification = StatementClassifier.classify(plan);
    jobsLogs.logExecutionStart(jobId, statement, sessionContext.sessionUser(), classification);
    JobsLogsUpdateListener jobsLogsUpdateListener = new JobsLogsUpdateListener(jobId, jobsLogs);
    if (!analyzedStatement.isWriteOperation()) {
        resultReceiver = new RetryOnFailureResultReceiver(executor.clusterService(), clusterState, // clusterState at the time of the index check is used
        indexName -> clusterState.metadata().hasIndex(indexName), resultReceiver, jobId, (newJobId, retryResultReceiver) -> retryQuery(newJobId, analyzedStatement, routingProvider, new RowConsumerToResultReceiver(retryResultReceiver, 0, jobsLogsUpdateListener), params, txnCtx, nodeCtx));
    }
    RowConsumerToResultReceiver consumer = new RowConsumerToResultReceiver(resultReceiver, 0, jobsLogsUpdateListener);
    plan.execute(executor, plannerContext, consumer, params, SubQueryResults.EMPTY);
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) Analyzer(io.crate.analyze.Analyzer) DependencyCarrier(io.crate.planner.DependencyCarrier) ClusterState(org.elasticsearch.cluster.ClusterState) Relations(io.crate.analyze.Relations) RowN(io.crate.data.RowN) TransactionState(io.crate.protocols.postgres.TransactionState) Map(java.util.Map) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) AnalyzedStatement(io.crate.analyze.AnalyzedStatement) UUIDs(org.elasticsearch.common.UUIDs) UUID(java.util.UUID) Lists2(io.crate.common.collections.Lists2) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AnalyzedDiscard(io.crate.analyze.AnalyzedDiscard) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) AnalyzedBegin(io.crate.analyze.AnalyzedBegin) SubQueryResults(io.crate.planner.operators.SubQueryResults) Statement(io.crate.sql.tree.Statement) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) AnalyzedCommit(io.crate.analyze.AnalyzedCommit) AccessControl(io.crate.auth.AccessControl) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Portal(io.crate.protocols.postgres.Portal) Symbols(io.crate.expression.symbol.Symbols) FormatCodes(io.crate.protocols.postgres.FormatCodes) SqlParser(io.crate.sql.parser.SqlParser) Nullable(javax.annotation.Nullable) Iterator(java.util.Iterator) RelationInfo(io.crate.metadata.RelationInfo) Target(io.crate.sql.tree.DiscardStatement.Target) DataType(io.crate.types.DataType) Planner(io.crate.planner.Planner) RoutingProvider(io.crate.metadata.RoutingProvider) RowConsumer(io.crate.data.RowConsumer) StatementClassifier(io.crate.planner.operators.StatementClassifier) AbstractTableRelation(io.crate.analyze.relations.AbstractTableRelation) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) ReadOnlyException(io.crate.exceptions.ReadOnlyException) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Randomness(org.elasticsearch.common.Randomness) AnalyzedDeallocate(io.crate.analyze.AnalyzedDeallocate) RoutingProvider(io.crate.metadata.RoutingProvider) ClusterState(org.elasticsearch.cluster.ClusterState) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) AnalyzedStatement(io.crate.analyze.AnalyzedStatement) Statement(io.crate.sql.tree.Statement) Plan(io.crate.planner.Plan) StatementClassifier(io.crate.planner.operators.StatementClassifier) PlannerContext(io.crate.planner.PlannerContext) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) AnalyzedStatement(io.crate.analyze.AnalyzedStatement) UUID(java.util.UUID)

Example 28 with PlannerContext

use of io.crate.planner.PlannerContext in project crate by crate.

the class Session method bulkExec.

private CompletableFuture<?> bulkExec(Statement statement, List<DeferredExecution> toExec) {
    assert toExec.size() >= 1 : "Must have at least 1 deferred execution for bulk exec";
    var jobId = UUIDs.dirtyUUID();
    var routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    var clusterState = executor.clusterService().state();
    var txnCtx = new CoordinatorTxnCtx(sessionContext);
    var plannerContext = new PlannerContext(clusterState, routingProvider, jobId, txnCtx, nodeCtx, 0, null);
    PreparedStmt firstPreparedStatement = toExec.get(0).portal().preparedStmt();
    AnalyzedStatement analyzedStatement = firstPreparedStatement.analyzedStatement();
    Plan plan;
    try {
        plan = planner.plan(analyzedStatement, plannerContext);
    } catch (Throwable t) {
        jobsLogs.logPreExecutionFailure(jobId, firstPreparedStatement.rawStatement(), SQLExceptions.messageOf(t), sessionContext.sessionUser());
        throw t;
    }
    jobsLogs.logExecutionStart(jobId, firstPreparedStatement.rawStatement(), sessionContext.sessionUser(), StatementClassifier.classify(plan));
    var bulkArgs = Lists2.map(toExec, x -> (Row) new RowN(x.portal().params().toArray()));
    List<CompletableFuture<Long>> rowCounts = plan.executeBulk(executor, plannerContext, bulkArgs, SubQueryResults.EMPTY);
    CompletableFuture<Void> allRowCounts = CompletableFuture.allOf(rowCounts.toArray(new CompletableFuture[0]));
    List<CompletableFuture<?>> resultReceiverFutures = Lists2.map(toExec, x -> x.resultReceiver().completionFuture());
    CompletableFuture<Void> allResultReceivers = CompletableFuture.allOf(resultReceiverFutures.toArray(new CompletableFuture[0]));
    return allRowCounts.exceptionally(// swallow exception - failures are set per item in emitResults
    t -> null).thenAccept(ignored -> emitRowCountsToResultReceivers(jobId, jobsLogs, toExec, rowCounts)).runAfterBoth(allResultReceivers, () -> {
    });
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) Analyzer(io.crate.analyze.Analyzer) DependencyCarrier(io.crate.planner.DependencyCarrier) ClusterState(org.elasticsearch.cluster.ClusterState) Relations(io.crate.analyze.Relations) RowN(io.crate.data.RowN) TransactionState(io.crate.protocols.postgres.TransactionState) Map(java.util.Map) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) AnalyzedStatement(io.crate.analyze.AnalyzedStatement) UUIDs(org.elasticsearch.common.UUIDs) UUID(java.util.UUID) Lists2(io.crate.common.collections.Lists2) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AnalyzedDiscard(io.crate.analyze.AnalyzedDiscard) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) AnalyzedBegin(io.crate.analyze.AnalyzedBegin) SubQueryResults(io.crate.planner.operators.SubQueryResults) Statement(io.crate.sql.tree.Statement) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) AnalyzedCommit(io.crate.analyze.AnalyzedCommit) AccessControl(io.crate.auth.AccessControl) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Portal(io.crate.protocols.postgres.Portal) Symbols(io.crate.expression.symbol.Symbols) FormatCodes(io.crate.protocols.postgres.FormatCodes) SqlParser(io.crate.sql.parser.SqlParser) Nullable(javax.annotation.Nullable) Iterator(java.util.Iterator) RelationInfo(io.crate.metadata.RelationInfo) Target(io.crate.sql.tree.DiscardStatement.Target) DataType(io.crate.types.DataType) Planner(io.crate.planner.Planner) RoutingProvider(io.crate.metadata.RoutingProvider) RowConsumer(io.crate.data.RowConsumer) StatementClassifier(io.crate.planner.operators.StatementClassifier) AbstractTableRelation(io.crate.analyze.relations.AbstractTableRelation) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) ReadOnlyException(io.crate.exceptions.ReadOnlyException) SQLExceptions(io.crate.exceptions.SQLExceptions) LogManager(org.apache.logging.log4j.LogManager) Randomness(org.elasticsearch.common.Randomness) AnalyzedDeallocate(io.crate.analyze.AnalyzedDeallocate) RoutingProvider(io.crate.metadata.RoutingProvider) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Plan(io.crate.planner.Plan) RowN(io.crate.data.RowN) CompletableFuture(java.util.concurrent.CompletableFuture) PlannerContext(io.crate.planner.PlannerContext) AnalyzedStatement(io.crate.analyze.AnalyzedStatement)

Example 29 with PlannerContext

use of io.crate.planner.PlannerContext in project crate by crate.

the class CreateAnalyzerPlan method executeOrFail.

@Override
public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) {
    ClusterUpdateSettingsRequest request = createRequest(createAnalyzer, plannerContext.transactionContext(), dependencies.nodeContext(), params, subQueryResults, dependencies.fulltextAnalyzerResolver());
    dependencies.transportActionProvider().transportClusterUpdateSettingsAction().execute(request, new OneRowActionListener<>(consumer, r -> new Row1(1L)));
}
Also used : TOKEN_FILTER(io.crate.metadata.FulltextAnalyzerResolver.CustomType.TOKEN_FILTER) Tuple(io.crate.common.collections.Tuple) HashMap(java.util.HashMap) GenericProperties(io.crate.sql.tree.GenericProperties) Function(java.util.function.Function) GenericProperty(io.crate.sql.tree.GenericProperty) DependencyCarrier(io.crate.planner.DependencyCarrier) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) ClusterUpdateSettingsRequest(org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest) Settings(org.elasticsearch.common.settings.Settings) Locale(java.util.Locale) Map(java.util.Map) GenericPropertiesConverter(io.crate.analyze.GenericPropertiesConverter) CHAR_FILTER(io.crate.metadata.FulltextAnalyzerResolver.CustomType.CHAR_FILTER) OneRowActionListener(io.crate.execution.support.OneRowActionListener) FulltextAnalyzerResolver(io.crate.metadata.FulltextAnalyzerResolver) Nullable(javax.annotation.Nullable) NodeContext(io.crate.metadata.NodeContext) AnalyzedCreateAnalyzer(io.crate.analyze.AnalyzedCreateAnalyzer) FulltextAnalyzerResolver.encodeSettings(io.crate.metadata.FulltextAnalyzerResolver.encodeSettings) TOKENIZER(io.crate.metadata.FulltextAnalyzerResolver.CustomType.TOKENIZER) RowConsumer(io.crate.data.RowConsumer) List(java.util.List) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) ANALYZER(io.crate.metadata.FulltextAnalyzerResolver.CustomType.ANALYZER) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Row1(io.crate.data.Row1) ClusterUpdateSettingsRequest(org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest)

Example 30 with PlannerContext

use of io.crate.planner.PlannerContext in project crate by crate.

the class CreateFunctionPlan method executeOrFail.

@Override
public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) throws Exception {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(plannerContext.transactionContext(), plannerContext.nodeContext(), x, params, subQueryResults);
    UserDefinedFunctionMetadata metadata = new UserDefinedFunctionMetadata(createFunction.schema(), createFunction.name(), createFunction.arguments(), createFunction.returnType(), StringType.INSTANCE.sanitizeValue(eval.apply(createFunction.language())), StringType.INSTANCE.sanitizeValue(eval.apply(createFunction.definition())));
    CreateUserDefinedFunctionRequest request = new CreateUserDefinedFunctionRequest(metadata, createFunction.replace());
    OneRowActionListener<AcknowledgedResponse> listener = new OneRowActionListener<>(consumer, r -> new Row1(1L));
    dependencies.createFunctionAction().execute(request, listener);
}
Also used : CreateUserDefinedFunctionRequest(io.crate.expression.udf.CreateUserDefinedFunctionRequest) StringType(io.crate.types.StringType) AnalyzedCreateFunction(io.crate.analyze.AnalyzedCreateFunction) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Function(java.util.function.Function) RowConsumer(io.crate.data.RowConsumer) DependencyCarrier(io.crate.planner.DependencyCarrier) UserDefinedFunctionMetadata(io.crate.expression.udf.UserDefinedFunctionMetadata) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) OneRowActionListener(io.crate.execution.support.OneRowActionListener) Row1(io.crate.data.Row1) Row1(io.crate.data.Row1) OneRowActionListener(io.crate.execution.support.OneRowActionListener) UserDefinedFunctionMetadata(io.crate.expression.udf.UserDefinedFunctionMetadata) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) CreateUserDefinedFunctionRequest(io.crate.expression.udf.CreateUserDefinedFunctionRequest)

Aggregations

PlannerContext (io.crate.planner.PlannerContext)40 Row (io.crate.data.Row)31 DependencyCarrier (io.crate.planner.DependencyCarrier)30 RowConsumer (io.crate.data.RowConsumer)29 Plan (io.crate.planner.Plan)28 SubQueryResults (io.crate.planner.operators.SubQueryResults)27 Row1 (io.crate.data.Row1)26 Symbol (io.crate.expression.symbol.Symbol)24 Function (java.util.function.Function)22 SymbolEvaluator (io.crate.analyze.SymbolEvaluator)19 OneRowActionListener (io.crate.execution.support.OneRowActionListener)19 List (java.util.List)17 VisibleForTesting (io.crate.common.annotations.VisibleForTesting)15 ArrayList (java.util.ArrayList)15 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)13 Map (java.util.Map)13 NodeContext (io.crate.metadata.NodeContext)12 DocTableInfo (io.crate.metadata.doc.DocTableInfo)12 Nullable (javax.annotation.Nullable)12 AbstractTableRelation (io.crate.analyze.relations.AbstractTableRelation)10