Search in sources :

Example 16 with EvaluatingNormalizer

use of io.crate.expression.eval.EvaluatingNormalizer in project crate by crate.

the class TableFunction method build.

@Override
public ExecutionPlan build(PlannerContext plannerContext, Set<PlanHint> planHints, ProjectionBuilder projectionBuilder, int limit, int offset, @Nullable OrderBy order, @Nullable Integer pageSizeHint, Row params, SubQueryResults subQueryResults) {
    List<Symbol> args = relation.function().arguments();
    ArrayList<Literal<?>> functionArguments = new ArrayList<>(args.size());
    EvaluatingNormalizer normalizer = new EvaluatingNormalizer(plannerContext.nodeContext(), RowGranularity.CLUSTER, null, relation);
    var binder = new SubQueryAndParamBinder(params, subQueryResults).andThen(x -> normalizer.normalize(x, plannerContext.transactionContext()));
    for (Symbol arg : args) {
        // It's not possible to use columns as argument to a table function, so it's safe to evaluate at this point.
        functionArguments.add(Literal.ofUnchecked(arg.valueType(), SymbolEvaluator.evaluate(plannerContext.transactionContext(), plannerContext.nodeContext(), arg, params, subQueryResults)));
    }
    TableFunctionCollectPhase collectPhase = new TableFunctionCollectPhase(plannerContext.jobId(), plannerContext.nextExecutionPhaseId(), plannerContext.handlerNode(), relation.functionImplementation(), functionArguments, Lists2.map(toCollect, binder), binder.apply(where.queryOrFallback()));
    return new Collect(collectPhase, TopN.NO_LIMIT, 0, toCollect.size(), TopN.NO_LIMIT, null);
}
Also used : EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) Collect(io.crate.planner.node.dql.Collect) SelectSymbol(io.crate.expression.symbol.SelectSymbol) Symbol(io.crate.expression.symbol.Symbol) Literal(io.crate.expression.symbol.Literal) ArrayList(java.util.ArrayList) TableFunctionCollectPhase(io.crate.execution.dsl.phases.TableFunctionCollectPhase)

Example 17 with EvaluatingNormalizer

use of io.crate.expression.eval.EvaluatingNormalizer in project crate by crate.

the class WhereClauseAnalyzer method tieBreakPartitionQueries.

@Nullable
private static PartitionResult tieBreakPartitionQueries(EvaluatingNormalizer normalizer, Map<Symbol, List<Literal>> queryPartitionMap, CoordinatorTxnCtx coordinatorTxnCtx) throws UnsupportedOperationException {
    /*
         * Got multiple normalized queries which all could match.
         * This might be the case if one partition resolved to null
         *
         * e.g.
         *
         *  p = 1 and x = 2
         *
         * might lead to
         *
         *  null and x = 2
         *  true and x = 2
         *
         * At this point it is unknown if they really match.
         * In order to figure out if they could potentially match all conditions involving references are now set to true
         *
         *  null and true   -> can't match
         *  true and true   -> can match, can use this query + partition
         *
         * If there is still more than 1 query that can match it's not possible to execute the query :(
         */
    List<Tuple<Symbol, List<Literal>>> canMatch = new ArrayList<>();
    for (Map.Entry<Symbol, List<Literal>> entry : queryPartitionMap.entrySet()) {
        Symbol query = entry.getKey();
        List<Literal> partitions = entry.getValue();
        Symbol normalized = normalizer.normalize(ScalarsAndRefsToTrue.rewrite(query), coordinatorTxnCtx);
        assert normalized instanceof Literal : "after normalization and replacing all reference occurrences with true there must only be a literal left";
        Object value = ((Literal) normalized).value();
        if (value != null && (Boolean) value) {
            canMatch.add(new Tuple<>(query, partitions));
        }
    }
    if (canMatch.size() == 1) {
        Tuple<Symbol, List<Literal>> symbolListTuple = canMatch.get(0);
        return new PartitionResult(symbolListTuple.v1(), Lists2.map(symbolListTuple.v2(), literal -> nullOrString(literal.value())));
    }
    return null;
}
Also used : Tuple(io.crate.common.collections.Tuple) ScalarsAndRefsToTrue(io.crate.analyze.ScalarsAndRefsToTrue) HashMap(java.util.HashMap) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) PartitionName(io.crate.metadata.PartitionName) ArrayList(java.util.ArrayList) Map(java.util.Map) StringUtils.nullOrString(io.crate.common.StringUtils.nullOrString) Nullable(javax.annotation.Nullable) DocTableInfo(io.crate.metadata.doc.DocTableInfo) NodeContext(io.crate.metadata.NodeContext) WhereClause(io.crate.analyze.WhereClause) PartitionReferenceResolver(io.crate.metadata.PartitionReferenceResolver) Reference(io.crate.metadata.Reference) Iterables(io.crate.common.collections.Iterables) Lists2(io.crate.common.collections.Lists2) List(java.util.List) RowGranularity(io.crate.metadata.RowGranularity) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) AbstractTableRelation(io.crate.analyze.relations.AbstractTableRelation) PartitionExpression(io.crate.expression.reference.partitioned.PartitionExpression) Collections(java.util.Collections) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Symbol(io.crate.expression.symbol.Symbol) ArrayList(java.util.ArrayList) Literal(io.crate.expression.symbol.Literal) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Tuple(io.crate.common.collections.Tuple) Nullable(javax.annotation.Nullable)

Example 18 with EvaluatingNormalizer

use of io.crate.expression.eval.EvaluatingNormalizer in project crate by crate.

the class UpdateAnalyzer method analyze.

public AnalyzedUpdateStatement analyze(Update update, ParamTypeHints typeHints, CoordinatorTxnCtx txnCtx) {
    /* UPDATE t1 SET col1 = ?, col2 = ? WHERE id = ?`
         *               ^^^^^^^^^^^^^^^^^^       ^^^^^^
         *               assignments               whereClause
         *
         *               col1 = ?
         *               |      |
         *               |     source
         *             columnName/target
         */
    StatementAnalysisContext stmtCtx = new StatementAnalysisContext(typeHints, Operation.UPDATE, txnCtx);
    final RelationAnalysisContext relCtx = stmtCtx.startRelation();
    AnalyzedRelation relation = relationAnalyzer.analyze(update.relation(), stmtCtx);
    stmtCtx.endRelation();
    MaybeAliasedStatement maybeAliasedStatement = MaybeAliasedStatement.analyze(relation);
    relation = maybeAliasedStatement.nonAliasedRelation();
    if (!(relation instanceof AbstractTableRelation)) {
        throw new UnsupportedOperationException("UPDATE is only supported on base-tables");
    }
    AbstractTableRelation<?> table = (AbstractTableRelation<?>) relation;
    EvaluatingNormalizer normalizer = new EvaluatingNormalizer(nodeCtx, RowGranularity.CLUSTER, null, table);
    SubqueryAnalyzer subqueryAnalyzer = new SubqueryAnalyzer(relationAnalyzer, new StatementAnalysisContext(typeHints, Operation.READ, txnCtx));
    ExpressionAnalyzer sourceExprAnalyzer = new ExpressionAnalyzer(txnCtx, nodeCtx, typeHints, new FullQualifiedNameFieldProvider(relCtx.sources(), relCtx.parentSources(), txnCtx.sessionContext().searchPath().currentSchema()), subqueryAnalyzer);
    ExpressionAnalysisContext exprCtx = new ExpressionAnalysisContext(txnCtx.sessionContext());
    Map<Reference, Symbol> assignmentByTargetCol = getAssignments(update.assignments(), typeHints, txnCtx, table, normalizer, subqueryAnalyzer, sourceExprAnalyzer, exprCtx);
    Symbol query = Objects.requireNonNullElse(sourceExprAnalyzer.generateQuerySymbol(update.whereClause(), exprCtx), Literal.BOOLEAN_TRUE);
    query = maybeAliasedStatement.maybeMapFields(query);
    Symbol normalizedQuery = normalizer.normalize(query, txnCtx);
    SelectAnalysis selectAnalysis = SelectAnalyzer.analyzeSelectItems(update.returningClause(), relCtx.sources(), sourceExprAnalyzer, exprCtx);
    List<Symbol> outputSymbol = Lists2.map(selectAnalysis.outputSymbols(), x -> normalizer.normalize(x, txnCtx));
    return new AnalyzedUpdateStatement(table, assignmentByTargetCol, normalizedQuery, outputSymbol.isEmpty() ? null : outputSymbol);
}
Also used : RelationAnalysisContext(io.crate.analyze.relations.RelationAnalysisContext) SelectAnalysis(io.crate.analyze.relations.select.SelectAnalysis) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) Reference(io.crate.metadata.Reference) Symbol(io.crate.expression.symbol.Symbol) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) StatementAnalysisContext(io.crate.analyze.relations.StatementAnalysisContext) SubqueryAnalyzer(io.crate.analyze.expressions.SubqueryAnalyzer) AbstractTableRelation(io.crate.analyze.relations.AbstractTableRelation) FullQualifiedNameFieldProvider(io.crate.analyze.relations.FullQualifiedNameFieldProvider)

Example 19 with EvaluatingNormalizer

use of io.crate.expression.eval.EvaluatingNormalizer in project crate by crate.

the class OptimizeCollectWhereClauseAccess method apply.

@Override
public LogicalPlan apply(Collect collect, Captures captures, TableStats tableStats, TransactionContext txnCtx, NodeContext nodeCtx) {
    var relation = (DocTableRelation) collect.relation();
    var normalizer = new EvaluatingNormalizer(nodeCtx, RowGranularity.CLUSTER, null, relation);
    WhereClause where = collect.where();
    var detailedQuery = WhereClauseOptimizer.optimize(normalizer, where.queryOrFallback(), relation.tableInfo(), txnCtx, nodeCtx);
    Optional<DocKeys> docKeys = detailedQuery.docKeys();
    // noinspection OptionalIsPresent no capturing lambda allocation
    if (docKeys.isPresent()) {
        return new Get(relation, docKeys.get(), detailedQuery.query(), collect.outputs(), tableStats.estimatedSizePerRow(relation.relationName()));
    } else if (!detailedQuery.clusteredBy().isEmpty() && collect.detailedQuery() == null) {
        return new Collect(collect, detailedQuery);
    } else {
        return null;
    }
}
Also used : EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) DocKeys(io.crate.analyze.where.DocKeys) Collect(io.crate.planner.operators.Collect) Get(io.crate.planner.operators.Get) WhereClause(io.crate.analyze.WhereClause) DocTableRelation(io.crate.analyze.relations.DocTableRelation)

Example 20 with EvaluatingNormalizer

use of io.crate.expression.eval.EvaluatingNormalizer in project crate by crate.

the class ProjectingRowConsumerTest method prepare.

@Before
public void prepare() {
    nodeCtx = createNodeContext();
    memoryManager = new OnHeapMemoryManager(usedBytes -> {
    });
    projectorFactory = new ProjectionToProjectorVisitor(clusterService, new NodeLimits(new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)), new NoneCircuitBreakerService(), nodeCtx, THREAD_POOL, Settings.EMPTY, mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS), new InputFactory(nodeCtx), new EvaluatingNormalizer(nodeCtx, RowGranularity.SHARD, r -> Literal.ofUnchecked(r.valueType(), r.valueType().implicitCast("1")), null), t -> null, t -> null, Version.CURRENT, new ShardId("dummy", UUID.randomUUID().toString(), 0), Map.of(LocalFsFileOutputFactory.NAME, new LocalFsFileOutputFactory()));
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) TransactionContext(io.crate.metadata.TransactionContext) java.util(java.util) InputColumn(io.crate.expression.symbol.InputColumn) SENTINEL(io.crate.data.SentinelRow.SENTINEL) CompletableFuture(java.util.concurrent.CompletableFuture) BatchIterator(io.crate.data.BatchIterator) SearchPath(io.crate.metadata.SearchPath) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) LocalFsFileOutputFactory(io.crate.execution.engine.export.LocalFsFileOutputFactory) NodeLimits(io.crate.execution.jobs.NodeLimits) Settings(org.elasticsearch.common.settings.Settings) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) UnhandledServerException(io.crate.exceptions.UnhandledServerException) TestingHelpers.createNodeContext(io.crate.testing.TestingHelpers.createNodeContext) Nullable(javax.annotation.Nullable) Before(org.junit.Before) NodeContext(io.crate.metadata.NodeContext) Answers(org.mockito.Answers) GroupProjection(io.crate.execution.dsl.projection.GroupProjection) FilterProjection(io.crate.execution.dsl.projection.FilterProjection) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) Test(org.junit.Test) EqOperator(io.crate.expression.operator.EqOperator) Function(io.crate.expression.symbol.Function) RamAccounting(io.crate.breaker.RamAccounting) TransportActionProvider(io.crate.execution.TransportActionProvider) RowConsumer(io.crate.data.RowConsumer) WriterProjection(io.crate.execution.dsl.projection.WriterProjection) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Version(org.elasticsearch.Version) RowGranularity(io.crate.metadata.RowGranularity) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) AggregateMode(io.crate.expression.symbol.AggregateMode) DataTypes(io.crate.types.DataTypes) Matchers.is(org.hamcrest.Matchers.is) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) InputFactory(io.crate.expression.InputFactory) TestingRowConsumer(io.crate.testing.TestingRowConsumer) Mockito.mock(org.mockito.Mockito.mock) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ShardId(org.elasticsearch.index.shard.ShardId) InputFactory(io.crate.expression.InputFactory) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) LocalFsFileOutputFactory(io.crate.execution.engine.export.LocalFsFileOutputFactory) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) NodeLimits(io.crate.execution.jobs.NodeLimits) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) Before(org.junit.Before)

Aggregations

EvaluatingNormalizer (io.crate.expression.eval.EvaluatingNormalizer)24 Symbol (io.crate.expression.symbol.Symbol)16 DocTableRelation (io.crate.analyze.relations.DocTableRelation)9 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)8 Test (org.junit.Test)7 RowGranularity (io.crate.metadata.RowGranularity)6 DocTableInfo (io.crate.metadata.doc.DocTableInfo)6 WhereClause (io.crate.analyze.WhereClause)5 ExpressionAnalysisContext (io.crate.analyze.expressions.ExpressionAnalysisContext)5 ExpressionAnalyzer (io.crate.analyze.expressions.ExpressionAnalyzer)5 Literal (io.crate.expression.symbol.Literal)5 NodeContext (io.crate.metadata.NodeContext)5 Routing (io.crate.metadata.Routing)5 ArrayList (java.util.ArrayList)5 Lists2 (io.crate.common.collections.Lists2)4 Nullable (javax.annotation.Nullable)4 AbstractTableRelation (io.crate.analyze.relations.AbstractTableRelation)3 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)3 FullQualifiedNameFieldProvider (io.crate.analyze.relations.FullQualifiedNameFieldProvider)3 RoutedCollectPhase (io.crate.execution.dsl.phases.RoutedCollectPhase)3