Search in sources :

Example 6 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx in project crate by crate.

the class AlterTableAddColumnPlan method bind.

@VisibleForTesting
public static BoundAddColumn bind(AnalyzedAlterTableAddColumn alterTable, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row params, SubQueryResults subQueryResults, FulltextAnalyzerResolver fulltextAnalyzerResolver) {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, params, subQueryResults);
    DocTableInfo tableInfo = alterTable.tableInfo();
    AnalyzedTableElements<Object> tableElements = alterTable.analyzedTableElements().map(eval);
    for (AnalyzedColumnDefinition<Object> column : tableElements.columns()) {
        ensureColumnLeafsAreNew(column, tableInfo);
    }
    addExistingPrimaryKeys(tableInfo, tableElements);
    ensureNoIndexDefinitions(tableElements.columns());
    addExistingCheckConstraints(tableInfo, tableElements);
    // validate table elements
    AnalyzedTableElements<Symbol> tableElementsUnboundWithExpressions = alterTable.analyzedTableElementsWithExpressions();
    Settings tableSettings = AnalyzedTableElements.validateAndBuildSettings(tableElements, fulltextAnalyzerResolver);
    Map<String, Object> mapping = AnalyzedTableElements.finalizeAndValidate(tableInfo.ident(), tableElementsUnboundWithExpressions, tableElements);
    int numCurrentPks = tableInfo.primaryKey().size();
    if (tableInfo.primaryKey().contains(DocSysColumns.ID)) {
        numCurrentPks -= 1;
    }
    boolean hasNewPrimaryKeys = AnalyzedTableElements.primaryKeys(tableElements).size() > numCurrentPks;
    boolean hasGeneratedColumns = tableElementsUnboundWithExpressions.hasGeneratedColumns();
    return new BoundAddColumn(tableInfo, tableElements, tableSettings, mapping, hasNewPrimaryKeys, hasGeneratedColumns);
}
Also used : AnalyzedColumnDefinition(io.crate.analyze.AnalyzedColumnDefinition) HashMap(java.util.HashMap) ObjectType(io.crate.types.ObjectType) Function(java.util.function.Function) ArrayList(java.util.ArrayList) DependencyCarrier(io.crate.planner.DependencyCarrier) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Settings(org.elasticsearch.common.settings.Settings) Locale(java.util.Locale) Map(java.util.Map) OneRowActionListener(io.crate.execution.support.OneRowActionListener) AnalyzedAlterTableAddColumn(io.crate.analyze.AnalyzedAlterTableAddColumn) FulltextAnalyzerResolver(io.crate.metadata.FulltextAnalyzerResolver) LinkedHashSet(java.util.LinkedHashSet) DocSysColumns(io.crate.metadata.doc.DocSysColumns) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) BoundAddColumn(io.crate.analyze.BoundAddColumn) ColumnIdent(io.crate.metadata.ColumnIdent) Reference(io.crate.metadata.Reference) CheckConstraint(io.crate.sql.tree.CheckConstraint) RowConsumer(io.crate.data.RowConsumer) Objects(java.util.Objects) AnalyzedTableElements(io.crate.analyze.AnalyzedTableElements) List(java.util.List) 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) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) DocTableInfo(io.crate.metadata.doc.DocTableInfo) Symbol(io.crate.expression.symbol.Symbol) CheckConstraint(io.crate.sql.tree.CheckConstraint) BoundAddColumn(io.crate.analyze.BoundAddColumn) Settings(org.elasticsearch.common.settings.Settings) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 7 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx in project crate by crate.

the class AlterTablePlan method bind.

public static BoundAlterTable bind(AnalyzedAlterTable analyzedAlterTable, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row params, SubQueryResults subQueryResults) {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, params, subQueryResults);
    DocTableInfo docTableInfo = analyzedAlterTable.tableInfo();
    AlterTable<Object> alterTable = analyzedAlterTable.alterTable().map(eval);
    Table<Object> table = alterTable.table();
    PartitionName partitionName = PartitionPropertiesAnalyzer.createPartitionName(table.partitionProperties(), docTableInfo);
    TableParameters tableParameters = getTableParameterInfo(table, partitionName);
    TableParameter tableParameter = getTableParameter(alterTable, tableParameters);
    maybeRaiseBlockedException(docTableInfo, tableParameter.settings());
    return new BoundAlterTable(docTableInfo, partitionName, tableParameter, table.excludePartitions(), docTableInfo.isPartitioned());
}
Also used : AlterTable(io.crate.sql.tree.AlterTable) AnalyzedAlterTable(io.crate.analyze.AnalyzedAlterTable) BoundAlterTable(io.crate.analyze.BoundAlterTable) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) PartitionPropertiesAnalyzer(io.crate.analyze.PartitionPropertiesAnalyzer) Operation(io.crate.metadata.table.Operation) Function(java.util.function.Function) PartitionName(io.crate.metadata.PartitionName) DependencyCarrier(io.crate.planner.DependencyCarrier) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Settings(org.elasticsearch.common.settings.Settings) OneRowActionListener(io.crate.execution.support.OneRowActionListener) Nullable(javax.annotation.Nullable) TableParameter(io.crate.analyze.TableParameter) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) TablePropertiesAnalyzer(io.crate.analyze.TablePropertiesAnalyzer) Table(io.crate.sql.tree.Table) TableParameters(io.crate.analyze.TableParameters) RowConsumer(io.crate.data.RowConsumer) 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) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) PartitionName(io.crate.metadata.PartitionName) DocTableInfo(io.crate.metadata.doc.DocTableInfo) BoundAlterTable(io.crate.analyze.BoundAlterTable) TableParameter(io.crate.analyze.TableParameter) TableParameters(io.crate.analyze.TableParameters)

Example 8 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx in project crate by crate.

the class UpdateById method createExecutor.

private ShardRequestExecutor<ShardUpsertRequest> createExecutor(DependencyCarrier dependencies, PlannerContext plannerContext) {
    ClusterService clusterService = dependencies.clusterService();
    CoordinatorTxnCtx txnCtx = plannerContext.transactionContext();
    ShardUpsertRequest.Builder requestBuilder = new ShardUpsertRequest.Builder(txnCtx.sessionSettings(), ShardingUpsertExecutor.BULK_REQUEST_TIMEOUT_SETTING.get(clusterService.state().metadata().settings()), ShardUpsertRequest.DuplicateKeyAction.UPDATE_OR_FAIL, true, assignments.targetNames(), // missing assignments are for INSERT .. ON DUPLICATE KEY UPDATE
    null, returnValues, plannerContext.jobId(), false);
    UpdateRequests updateRequests = new UpdateRequests(requestBuilder, table, assignments);
    return new ShardRequestExecutor<>(clusterService, txnCtx, dependencies.nodeContext(), table, updateRequests, dependencies.transportActionProvider().transportShardUpsertAction()::execute, docKeys);
}
Also used : CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRequestExecutor(io.crate.execution.dml.ShardRequestExecutor) ShardUpsertRequest(io.crate.execution.dml.upsert.ShardUpsertRequest)

Example 9 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx in project crate by crate.

the class Session method singleExec.

@VisibleForTesting
CompletableFuture<?> singleExec(Portal portal, ResultReceiver<?> resultReceiver, int maxRows) {
    var activeConsumer = portal.activeConsumer();
    if (activeConsumer != null && activeConsumer.suspended()) {
        activeConsumer.replaceResultReceiver(resultReceiver, maxRows);
        activeConsumer.resume();
        return resultReceiver.completionFuture();
    }
    var jobId = UUIDs.dirtyUUID();
    var routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    var clusterState = executor.clusterService().state();
    var txnCtx = new CoordinatorTxnCtx(sessionContext);
    var nodeCtx = executor.nodeContext();
    var params = new RowN(portal.params().toArray());
    var plannerContext = new PlannerContext(clusterState, routingProvider, jobId, txnCtx, nodeCtx, maxRows, params);
    var analyzedStmt = portal.analyzedStatement();
    String rawStatement = portal.preparedStmt().rawStatement();
    if (analyzedStmt == null) {
        String errorMsg = "Statement must have been analyzed: " + rawStatement;
        jobsLogs.logPreExecutionFailure(jobId, rawStatement, errorMsg, sessionContext.sessionUser());
        throw new IllegalStateException(errorMsg);
    }
    Plan plan;
    try {
        plan = planner.plan(analyzedStmt, plannerContext);
    } catch (Throwable t) {
        jobsLogs.logPreExecutionFailure(jobId, rawStatement, SQLExceptions.messageOf(t), sessionContext.sessionUser());
        throw t;
    }
    if (!analyzedStmt.isWriteOperation()) {
        resultReceiver = new RetryOnFailureResultReceiver(executor.clusterService(), clusterState, indexName -> executor.clusterService().state().metadata().hasIndex(indexName), resultReceiver, jobId, (newJobId, resultRec) -> retryQuery(newJobId, analyzedStmt, routingProvider, new RowConsumerToResultReceiver(resultRec, maxRows, new JobsLogsUpdateListener(newJobId, jobsLogs)), params, txnCtx, nodeCtx));
    }
    jobsLogs.logExecutionStart(jobId, rawStatement, sessionContext.sessionUser(), StatementClassifier.classify(plan));
    RowConsumerToResultReceiver consumer = new RowConsumerToResultReceiver(resultReceiver, maxRows, new JobsLogsUpdateListener(jobId, jobsLogs));
    portal.setActiveConsumer(consumer);
    plan.execute(executor, plannerContext, consumer, params, SubQueryResults.EMPTY);
    return resultReceiver.completionFuture();
}
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) PlannerContext(io.crate.planner.PlannerContext) JobsLogsUpdateListener(io.crate.protocols.postgres.JobsLogsUpdateListener) RetryOnFailureResultReceiver(io.crate.protocols.postgres.RetryOnFailureResultReceiver) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 10 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx in project crate by crate.

the class AlterTableAddColumnAnalyzer method analyze.

public AnalyzedAlterTableAddColumn analyze(AlterTableAddColumn<Expression> alterTable, ParamTypeHints paramTypeHints, CoordinatorTxnCtx txnCtx) {
    if (!alterTable.table().partitionProperties().isEmpty()) {
        throw new UnsupportedOperationException("Adding a column to a single partition is not supported");
    }
    DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo(alterTable.table().getName(), Operation.ALTER, txnCtx.sessionContext().sessionUser(), txnCtx.sessionContext().searchPath());
    TableReferenceResolver referenceResolver = new TableReferenceResolver(tableInfo.columns(), tableInfo.ident());
    var exprAnalyzerWithReferenceResolver = new ExpressionAnalyzer(txnCtx, nodeCtx, paramTypeHints, referenceResolver, null);
    var exprAnalyzerWithFieldsAsString = new ExpressionAnalyzer(txnCtx, nodeCtx, paramTypeHints, FieldProvider.FIELDS_AS_LITERAL, null);
    var exprCtx = new ExpressionAnalysisContext(txnCtx.sessionContext());
    AddColumnDefinition<Expression> tableElement = alterTable.tableElement();
    // convert and validate the column name
    ExpressionToColumnIdentVisitor.convert(tableElement.name());
    // 1st phase, exclude check constraints (their expressions contain column references) and generated expressions
    AddColumnDefinition<Symbol> addColumnDefinition = new AddColumnDefinition<>(exprAnalyzerWithFieldsAsString.convert(tableElement.name(), exprCtx), // expression must be mapped later on using mapExpressions()
    null, tableElement.type() == null ? null : tableElement.type().map(y -> exprAnalyzerWithFieldsAsString.convert(y, exprCtx)), tableElement.constraints().stream().filter(c -> false == c instanceof CheckColumnConstraint).map(x -> x.map(y -> exprAnalyzerWithFieldsAsString.convert(y, exprCtx))).collect(Collectors.toList()), false, tableElement.generatedExpression() != null);
    AnalyzedTableElements<Symbol> analyzedTableElements = TableElementsAnalyzer.analyze(singletonList(addColumnDefinition), tableInfo.ident(), tableInfo);
    // 2nd phase, analyze possible generated expressions
    AddColumnDefinition<Symbol> addColumnDefinitionWithExpression = (AddColumnDefinition<Symbol>) tableElement.mapExpressions(addColumnDefinition, x -> exprAnalyzerWithReferenceResolver.convert(x, exprCtx));
    AnalyzedTableElements<Symbol> analyzedTableElementsWithExpressions = TableElementsAnalyzer.analyze(singletonList(addColumnDefinitionWithExpression), tableInfo.ident(), tableInfo);
    // now analyze possible check expressions
    var checkColumnConstraintsAnalyzer = new ExpressionAnalyzer(txnCtx, nodeCtx, paramTypeHints, new SelfReferenceFieldProvider(tableInfo.ident(), referenceResolver, analyzedTableElements.columns()), null);
    tableElement.constraints().stream().filter(CheckColumnConstraint.class::isInstance).map(x -> x.map(y -> checkColumnConstraintsAnalyzer.convert(y, exprCtx))).forEach(c -> {
        CheckColumnConstraint<Symbol> check = (CheckColumnConstraint<Symbol>) c;
        analyzedTableElements.addCheckColumnConstraint(tableInfo.ident(), check);
        analyzedTableElementsWithExpressions.addCheckColumnConstraint(tableInfo.ident(), check);
    });
    return new AnalyzedAlterTableAddColumn(tableInfo, analyzedTableElements, analyzedTableElementsWithExpressions);
}
Also used : ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) AlterTableAddColumn(io.crate.sql.tree.AlterTableAddColumn) RelationName(io.crate.metadata.RelationName) FieldProvider(io.crate.analyze.relations.FieldProvider) Operation(io.crate.metadata.table.Operation) TableReferenceResolver(io.crate.analyze.expressions.TableReferenceResolver) Collections.singletonList(java.util.Collections.singletonList) Locale(java.util.Locale) ExpressionToColumnIdentVisitor(io.crate.analyze.expressions.ExpressionToColumnIdentVisitor) QualifiedName(io.crate.sql.tree.QualifiedName) Nullable(javax.annotation.Nullable) DocTableInfo(io.crate.metadata.doc.DocTableInfo) NodeContext(io.crate.metadata.NodeContext) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) ColumnIdent(io.crate.metadata.ColumnIdent) Reference(io.crate.metadata.Reference) CheckColumnConstraint(io.crate.sql.tree.CheckColumnConstraint) Collectors(java.util.stream.Collectors) List(java.util.List) RowGranularity(io.crate.metadata.RowGranularity) Symbol(io.crate.expression.symbol.Symbol) ColumnUnknownException(io.crate.exceptions.ColumnUnknownException) Schemas(io.crate.metadata.Schemas) ReferenceIdent(io.crate.metadata.ReferenceIdent) AddColumnDefinition(io.crate.sql.tree.AddColumnDefinition) Expression(io.crate.sql.tree.Expression) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) DocTableInfo(io.crate.metadata.doc.DocTableInfo) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) Symbol(io.crate.expression.symbol.Symbol) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) AddColumnDefinition(io.crate.sql.tree.AddColumnDefinition) Expression(io.crate.sql.tree.Expression) CheckColumnConstraint(io.crate.sql.tree.CheckColumnConstraint) TableReferenceResolver(io.crate.analyze.expressions.TableReferenceResolver)

Aggregations

CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)44 Symbol (io.crate.expression.symbol.Symbol)27 NodeContext (io.crate.metadata.NodeContext)22 List (java.util.List)16 PlannerContext (io.crate.planner.PlannerContext)15 ArrayList (java.util.ArrayList)15 Map (java.util.Map)14 Lists2 (io.crate.common.collections.Lists2)13 Row (io.crate.data.Row)13 RelationName (io.crate.metadata.RelationName)13 Plan (io.crate.planner.Plan)13 SubQueryResults (io.crate.planner.operators.SubQueryResults)13 Function (java.util.function.Function)13 VisibleForTesting (io.crate.common.annotations.VisibleForTesting)12 RowConsumer (io.crate.data.RowConsumer)12 DependencyCarrier (io.crate.planner.DependencyCarrier)12 HashMap (java.util.HashMap)12 Test (org.junit.Test)12 Row1 (io.crate.data.Row1)11 DocTableInfo (io.crate.metadata.doc.DocTableInfo)11