Search in sources :

Example 11 with Lists2.mapTail

use of io.crate.common.collections.Lists2.mapTail 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 12 with Lists2.mapTail

use of io.crate.common.collections.Lists2.mapTail in project crate by crate.

the class RestoreSnapshotPlan method bind.

@VisibleForTesting
public static BoundRestoreSnapshot bind(AnalyzedRestoreSnapshot restoreSnapshot, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row parameters, SubQueryResults subQueryResults, Schemas schemas) {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, parameters, subQueryResults);
    Settings settings = GenericPropertiesConverter.genericPropertiesToSettings(restoreSnapshot.properties().map(eval), SnapshotSettings.SETTINGS);
    HashSet<BoundRestoreSnapshot.RestoreTableInfo> restoreTables = new HashSet<>(restoreSnapshot.tables().size());
    for (Table<Symbol> table : restoreSnapshot.tables()) {
        var relationName = RelationName.of(table.getName(), txnCtx.sessionContext().searchPath().currentSchema());
        try {
            DocTableInfo docTableInfo = schemas.getTableInfo(relationName, Operation.RESTORE_SNAPSHOT);
            if (table.partitionProperties().isEmpty()) {
                throw new RelationAlreadyExists(relationName);
            }
            var partitionName = toPartitionName(docTableInfo, Lists2.map(table.partitionProperties(), x -> x.map(eval)));
            if (docTableInfo.partitions().contains(partitionName)) {
                throw new PartitionAlreadyExistsException(partitionName);
            }
            restoreTables.add(new BoundRestoreSnapshot.RestoreTableInfo(relationName, partitionName));
        } catch (RelationUnknown | SchemaUnknownException e) {
            if (table.partitionProperties().isEmpty()) {
                restoreTables.add(new BoundRestoreSnapshot.RestoreTableInfo(relationName, null));
            } else {
                var partitionName = toPartitionName(relationName, Lists2.map(table.partitionProperties(), x -> x.map(eval)));
                restoreTables.add(new BoundRestoreSnapshot.RestoreTableInfo(relationName, partitionName));
            }
        }
    }
    return new BoundRestoreSnapshot(restoreSnapshot.repository(), restoreSnapshot.snapshot(), restoreTables, restoreSnapshot.includeTables(), restoreSnapshot.includeCustomMetadata(), restoreSnapshot.customMetadataTypes(), restoreSnapshot.includeGlobalSettings(), restoreSnapshot.globalSettings(), settings);
}
Also used : PartitionAlreadyExistsException(io.crate.exceptions.PartitionAlreadyExistsException) IndexParts(io.crate.metadata.IndexParts) RelationName(io.crate.metadata.RelationName) CompletableFuture(java.util.concurrent.CompletableFuture) Operation(io.crate.metadata.table.Operation) GetSnapshotsRequest(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) Function(java.util.function.Function) PartitionName(io.crate.metadata.PartitionName) ArrayList(java.util.ArrayList) DependencyCarrier(io.crate.planner.DependencyCarrier) HashSet(java.util.HashSet) WAIT_FOR_COMPLETION(io.crate.analyze.SnapshotSettings.WAIT_FOR_COMPLETION) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Settings(org.elasticsearch.common.settings.Settings) RestoreSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) SchemaUnknownException(io.crate.exceptions.SchemaUnknownException) BoundRestoreSnapshot(io.crate.analyze.BoundRestoreSnapshot) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) GenericPropertiesConverter(io.crate.analyze.GenericPropertiesConverter) OneRowActionListener(io.crate.execution.support.OneRowActionListener) FutureActionListener(io.crate.action.FutureActionListener) PartitionPropertiesAnalyzer.toPartitionName(io.crate.analyze.PartitionPropertiesAnalyzer.toPartitionName) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) DocTableInfo(io.crate.metadata.doc.DocTableInfo) AnalyzedRestoreSnapshot(io.crate.analyze.AnalyzedRestoreSnapshot) NodeContext(io.crate.metadata.NodeContext) Table(io.crate.sql.tree.Table) Set(java.util.Set) Lists2(io.crate.common.collections.Lists2) SnapshotSettings(io.crate.analyze.SnapshotSettings) RowConsumer(io.crate.data.RowConsumer) List(java.util.List) Row(io.crate.data.Row) RelationAlreadyExists(io.crate.exceptions.RelationAlreadyExists) Symbol(io.crate.expression.symbol.Symbol) PlannerContext(io.crate.planner.PlannerContext) IGNORE_UNAVAILABLE(io.crate.analyze.SnapshotSettings.IGNORE_UNAVAILABLE) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) Schemas(io.crate.metadata.Schemas) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) RelationUnknown(io.crate.exceptions.RelationUnknown) TransportGetSnapshotsAction(org.elasticsearch.action.admin.cluster.snapshots.get.TransportGetSnapshotsAction) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) BoundRestoreSnapshot(io.crate.analyze.BoundRestoreSnapshot) DocTableInfo(io.crate.metadata.doc.DocTableInfo) RelationUnknown(io.crate.exceptions.RelationUnknown) Symbol(io.crate.expression.symbol.Symbol) SchemaUnknownException(io.crate.exceptions.SchemaUnknownException) RelationAlreadyExists(io.crate.exceptions.RelationAlreadyExists) Settings(org.elasticsearch.common.settings.Settings) SnapshotSettings(io.crate.analyze.SnapshotSettings) PartitionAlreadyExistsException(io.crate.exceptions.PartitionAlreadyExistsException) HashSet(java.util.HashSet) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 13 with Lists2.mapTail

use of io.crate.common.collections.Lists2.mapTail in project crate by crate.

the class CopyAnalyzer method analyzeCopyTo.

AnalyzedCopyTo analyzeCopyTo(CopyTo<Expression> node, ParamTypeHints paramTypeHints, CoordinatorTxnCtx txnCtx) {
    if (!node.directoryUri()) {
        throw new UnsupportedOperationException("Using COPY TO without specifying a DIRECTORY is not supported");
    }
    TableInfo tableInfo = schemas.resolveTableInfo(node.table().getName(), Operation.COPY_TO, txnCtx.sessionContext().sessionUser(), txnCtx.sessionContext().searchPath());
    Operation.blockedRaiseException(tableInfo, Operation.READ);
    DocTableRelation tableRelation = new DocTableRelation((DocTableInfo) tableInfo);
    EvaluatingNormalizer normalizer = new EvaluatingNormalizer(nodeCtx, RowGranularity.CLUSTER, null, tableRelation);
    var exprCtx = new ExpressionAnalysisContext(txnCtx.sessionContext());
    var expressionAnalyzer = new ExpressionAnalyzer(txnCtx, nodeCtx, paramTypeHints, new NameFieldProvider(tableRelation), null);
    var exprAnalyzerWithFieldsAsString = new ExpressionAnalyzer(txnCtx, nodeCtx, paramTypeHints, FieldProvider.FIELDS_AS_LITERAL, null);
    var uri = expressionAnalyzer.convert(node.targetUri(), exprCtx);
    var table = node.table().map(x -> exprAnalyzerWithFieldsAsString.convert(x, exprCtx));
    var properties = node.properties().map(x -> expressionAnalyzer.convert(x, exprCtx));
    var columns = Lists2.map(node.columns(), c -> normalizer.normalize(expressionAnalyzer.convert(c, exprCtx), txnCtx));
    var whereClause = node.whereClause().map(w -> normalizer.normalize(expressionAnalyzer.convert(w, exprCtx), txnCtx)).orElse(null);
    return new AnalyzedCopyTo(tableInfo, table, normalizer.normalize(uri, txnCtx), properties, columns, whereClause);
}
Also used : ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) TableRelation(io.crate.analyze.relations.TableRelation) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) FieldProvider(io.crate.analyze.relations.FieldProvider) CopyFrom(io.crate.sql.tree.CopyFrom) Table(io.crate.sql.tree.Table) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) GenericProperties(io.crate.sql.tree.GenericProperties) Operation(io.crate.metadata.table.Operation) Lists2(io.crate.common.collections.Lists2) CopyTo(io.crate.sql.tree.CopyTo) RowGranularity(io.crate.metadata.RowGranularity) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Symbol(io.crate.expression.symbol.Symbol) NameFieldProvider(io.crate.analyze.relations.NameFieldProvider) Schemas(io.crate.metadata.Schemas) Expression(io.crate.sql.tree.Expression) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) NameFieldProvider(io.crate.analyze.relations.NameFieldProvider) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) DocTableRelation(io.crate.analyze.relations.DocTableRelation) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo)

Example 14 with Lists2.mapTail

use of io.crate.common.collections.Lists2.mapTail in project crate by crate.

the class RelationAnalyzer method visitValues.

@Override
public AnalyzedRelation visitValues(Values values, StatementAnalysisContext context) {
    var expressionAnalyzer = new ExpressionAnalyzer(context.transactionContext(), nodeCtx, context.paramTyeHints(), FieldProvider.UNSUPPORTED, new SubqueryAnalyzer(this, context));
    var expressionAnalysisContext = new ExpressionAnalysisContext(context.sessionContext());
    // prevent normalization of the values array, otherwise the value literals are converted to an array literal
    // and a special per-value-literal casting logic won't be executed (e.g. FloatLiteral.cast())
    expressionAnalysisContext.allowEagerNormalize(false);
    java.util.function.Function<Expression, Symbol> expressionToSymbol = e -> expressionAnalyzer.convert(e, expressionAnalysisContext);
    // There is a first pass to convert expressions from row oriented format:
    // `[[1, a], [2, b]]` to columns `[[1, 2], [a, b]]`
    // 
    // At the same time we determine the column type with the highest precedence,
    // so that we don't fail with slight type miss-matches (long vs. int)
    List<ValuesList> rows = values.rows();
    assert rows.size() > 0 : "Parser grammar enforces at least 1 row";
    ValuesList firstRow = rows.get(0);
    int numColumns = firstRow.values().size();
    ArrayList<List<Symbol>> columns = new ArrayList<>();
    ArrayList<DataType<?>> targetTypes = new ArrayList<>(numColumns);
    var parentOutputColumns = context.parentOutputColumns();
    for (int c = 0; c < numColumns; c++) {
        ArrayList<Symbol> columnValues = new ArrayList<>();
        DataType<?> targetType;
        boolean usePrecedence = true;
        if (parentOutputColumns.size() > c) {
            targetType = parentOutputColumns.get(c).valueType();
            usePrecedence = false;
        } else {
            targetType = DataTypes.UNDEFINED;
        }
        for (int r = 0; r < rows.size(); r++) {
            List<Expression> row = rows.get(r).values();
            if (row.size() != numColumns) {
                throw new IllegalArgumentException("VALUES lists must all be the same length. " + "Found row with " + numColumns + " items and another with " + columns.size() + " items");
            }
            Symbol cell = expressionToSymbol.apply(row.get(c));
            columnValues.add(cell);
            var cellType = cell.valueType();
            if (// skip first cell, we don't have to check for self-conversion
            r > 0 && !cellType.isConvertableTo(targetType, false) && targetType.id() != DataTypes.UNDEFINED.id()) {
                throw new IllegalArgumentException("The types of the columns within VALUES lists must match. " + "Found `" + targetType + "` and `" + cellType + "` at position: " + c);
            }
            if (usePrecedence && cellType.precedes(targetType)) {
                targetType = cellType;
            } else if (targetType == DataTypes.UNDEFINED) {
                targetType = cellType;
            }
        }
        targetTypes.add(targetType);
        columns.add(columnValues);
    }
    var normalizer = EvaluatingNormalizer.functionOnlyNormalizer(nodeCtx, f -> f.isDeterministic());
    ArrayList<Symbol> arrays = new ArrayList<>(columns.size());
    for (int c = 0; c < numColumns; c++) {
        DataType<?> targetType = targetTypes.get(c);
        ArrayType<?> arrayType = new ArrayType<>(targetType);
        List<Symbol> columnValues = Lists2.map(columns.get(c), s -> normalizer.normalize(s.cast(targetType), context.transactionContext()));
        arrays.add(new Function(ArrayFunction.SIGNATURE, columnValues, arrayType));
    }
    FunctionImplementation implementation = nodeCtx.functions().getQualified(ValuesFunction.SIGNATURE, Symbols.typeView(arrays), RowType.EMPTY);
    Function function = new Function(implementation.signature(), arrays, RowType.EMPTY);
    TableFunctionImplementation<?> tableFunc = TableFunctionFactory.from(implementation);
    TableFunctionRelation relation = new TableFunctionRelation(tableFunc, function);
    context.startRelation();
    context.currentRelationContext().addSourceRelation(relation);
    context.endRelation();
    return relation;
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) JoinCriteria(io.crate.sql.tree.JoinCriteria) UnsupportedFeatureException(io.crate.exceptions.UnsupportedFeatureException) RelationName(io.crate.metadata.RelationName) RowType(io.crate.types.RowType) DefaultTraversalVisitor(io.crate.sql.tree.DefaultTraversalVisitor) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) Node(io.crate.sql.tree.Node) ArrayType(io.crate.types.ArrayType) JoinType(io.crate.planner.node.dql.join.JoinType) JoinOn(io.crate.sql.tree.JoinOn) Locale(java.util.Locale) Map(java.util.Map) SelectAnalysis(io.crate.analyze.relations.select.SelectAnalysis) ValuesList(io.crate.sql.tree.ValuesList) Union(io.crate.sql.tree.Union) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) SortItem(io.crate.sql.tree.SortItem) Collection(java.util.Collection) QuerySpecification(io.crate.sql.tree.QuerySpecification) TableSubquery(io.crate.sql.tree.TableSubquery) Set(java.util.Set) SelectAnalyzer(io.crate.analyze.relations.select.SelectAnalyzer) Intersect(io.crate.sql.tree.Intersect) WhereClauseValidator(io.crate.analyze.where.WhereClauseValidator) Iterables(io.crate.common.collections.Iterables) Lists2(io.crate.common.collections.Lists2) Relation(io.crate.sql.tree.Relation) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) DataTypes(io.crate.types.DataTypes) Singleton(org.elasticsearch.common.inject.Singleton) Values(io.crate.sql.tree.Values) Optional(java.util.Optional) Expression(io.crate.sql.tree.Expression) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) SemanticSortValidator(io.crate.analyze.validator.SemanticSortValidator) AmbiguousColumnAliasException(io.crate.exceptions.AmbiguousColumnAliasException) Tuple(io.crate.common.collections.Tuple) SubqueryAnalyzer(io.crate.analyze.expressions.SubqueryAnalyzer) FunctionCall(io.crate.sql.tree.FunctionCall) QualifiedNameReference(io.crate.sql.tree.QualifiedNameReference) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) SearchPath(io.crate.metadata.SearchPath) Operation(io.crate.metadata.table.Operation) HavingSymbolValidator(io.crate.analyze.validator.HavingSymbolValidator) AliasedRelation(io.crate.sql.tree.AliasedRelation) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ValuesFunction(io.crate.expression.tablefunctions.ValuesFunction) Join(io.crate.sql.tree.Join) Symbols(io.crate.expression.symbol.Symbols) SqlParser(io.crate.sql.parser.SqlParser) Query(io.crate.sql.tree.Query) QualifiedName(io.crate.sql.tree.QualifiedName) TableFunction(io.crate.sql.tree.TableFunction) Nullable(javax.annotation.Nullable) RelationValidationException(io.crate.exceptions.RelationValidationException) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) OrderByWithAggregationValidator(io.crate.planner.consumer.OrderByWithAggregationValidator) ViewMetadata(io.crate.metadata.view.ViewMetadata) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) TableFunctionFactory(io.crate.expression.tablefunctions.TableFunctionFactory) Table(io.crate.sql.tree.Table) DataType(io.crate.types.DataType) Function(io.crate.expression.symbol.Function) GroupAndAggregateSemantics(io.crate.expression.symbol.GroupAndAggregateSemantics) JoinUsing(io.crate.sql.tree.JoinUsing) TableFunctionImplementation(io.crate.metadata.tablefunctions.TableFunctionImplementation) Except(io.crate.sql.tree.Except) Literal(io.crate.expression.symbol.Literal) GroupBySymbolValidator(io.crate.analyze.validator.GroupBySymbolValidator) ColumnUnknownException(io.crate.exceptions.ColumnUnknownException) Schemas(io.crate.metadata.Schemas) RelationUnknown(io.crate.exceptions.RelationUnknown) Collections(java.util.Collections) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) Symbol(io.crate.expression.symbol.Symbol) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) ArrayList(java.util.ArrayList) ArrayType(io.crate.types.ArrayType) ValuesFunction(io.crate.expression.tablefunctions.ValuesFunction) TableFunction(io.crate.sql.tree.TableFunction) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) Function(io.crate.expression.symbol.Function) DataType(io.crate.types.DataType) ValuesList(io.crate.sql.tree.ValuesList) List(java.util.List) ArrayList(java.util.ArrayList) FunctionImplementation(io.crate.metadata.FunctionImplementation) TableFunctionImplementation(io.crate.metadata.tablefunctions.TableFunctionImplementation) ValuesList(io.crate.sql.tree.ValuesList) Expression(io.crate.sql.tree.Expression) SubqueryAnalyzer(io.crate.analyze.expressions.SubqueryAnalyzer)

Example 15 with Lists2.mapTail

use of io.crate.common.collections.Lists2.mapTail 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)

Aggregations

Lists2 (io.crate.common.collections.Lists2)21 Symbol (io.crate.expression.symbol.Symbol)17 List (java.util.List)17 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)13 Map (java.util.Map)13 NodeContext (io.crate.metadata.NodeContext)12 ArrayList (java.util.ArrayList)12 Row (io.crate.data.Row)10 DocTableInfo (io.crate.metadata.doc.DocTableInfo)10 Nullable (javax.annotation.Nullable)10 RelationName (io.crate.metadata.RelationName)8 SubQueryResults (io.crate.planner.operators.SubQueryResults)8 HashMap (java.util.HashMap)8 Function (java.util.function.Function)8 Literal (io.crate.expression.symbol.Literal)7 PlannerContext (io.crate.planner.PlannerContext)7 DataType (io.crate.types.DataType)7 Schemas (io.crate.metadata.Schemas)6 RowConsumer (io.crate.data.RowConsumer)5 EvaluatingNormalizer (io.crate.expression.eval.EvaluatingNormalizer)5