Search in sources :

Example 21 with CoordinatorTxnCtx

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

the class ExpressionAnalyzerTest method testAnalyzeArraySliceFunctionCall.

@Test
public void testAnalyzeArraySliceFunctionCall() {
    ReferenceIdent arrayRefIdent = new ReferenceIdent(new RelationName("doc", "tarr"), "xs");
    Reference arrayRef = new Reference(arrayRefIdent, RowGranularity.DOC, DataTypes.INTEGER_ARRAY, ColumnPolicy.DYNAMIC, Reference.IndexType.PLAIN, true, true, 1, null);
    CoordinatorTxnCtx txnCtx = CoordinatorTxnCtx.systemTransactionContext();
    ExpressionAnalysisContext localContext = new ExpressionAnalysisContext(txnCtx.sessionContext());
    Symbol function = ExpressionAnalyzer.allocateFunction(ArraySliceFunction.NAME, List.of(arrayRef, Literal.of(1), Literal.of(3)), null, localContext, txnCtx, expressions.nodeCtx);
    var result = executor.asSymbol("tarr.xs[1:3]");
    assertThat(result, is(equalTo(function)));
}
Also used : CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) SymbolMatchers.isReference(io.crate.testing.SymbolMatchers.isReference) Reference(io.crate.metadata.Reference) ParameterSymbol(io.crate.expression.symbol.ParameterSymbol) ScopedSymbol(io.crate.expression.symbol.ScopedSymbol) Symbol(io.crate.expression.symbol.Symbol) RelationName(io.crate.metadata.RelationName) ReferenceIdent(io.crate.metadata.ReferenceIdent) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 22 with CoordinatorTxnCtx

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

the class ExpressionAnalyzerTest method testInSelfJoinCaseFunctionsThatLookTheSameMustNotReuseFunctionAllocation.

@Test
public void testInSelfJoinCaseFunctionsThatLookTheSameMustNotReuseFunctionAllocation() throws Exception {
    TableInfo t1 = executor.resolveTableInfo("t1");
    TableRelation relation = new TableRelation(t1);
    RelationName a1 = new RelationName(null, "a1");
    RelationName a2 = new RelationName(null, "a2");
    Map<RelationName, AnalyzedRelation> sources = Map.of(a1, new AliasedAnalyzedRelation(relation, a1), a2, new AliasedAnalyzedRelation(relation, a2));
    SessionContext sessionContext = SessionContext.systemSessionContext();
    CoordinatorTxnCtx coordinatorTxnCtx = new CoordinatorTxnCtx(sessionContext);
    ExpressionAnalyzer expressionAnalyzer = new ExpressionAnalyzer(coordinatorTxnCtx, expressions.nodeCtx, paramTypeHints, new FullQualifiedNameFieldProvider(sources, ParentRelations.NO_PARENTS, sessionContext.searchPath().currentSchema()), null);
    Function andFunction = (Function) expressionAnalyzer.convert(SqlParser.createExpression("not a1.x = 1 and not a2.x = 1"), context);
    ScopedSymbol t1Id = ((ScopedSymbol) ((Function) ((Function) andFunction.arguments().get(0)).arguments().get(0)).arguments().get(0));
    ScopedSymbol t2Id = ((ScopedSymbol) ((Function) ((Function) andFunction.arguments().get(1)).arguments().get(0)).arguments().get(0));
    assertThat(t1Id.relation(), is(not(t2Id.relation())));
}
Also used : CoalesceFunction(io.crate.expression.scalar.conditional.CoalesceFunction) SymbolMatchers.isFunction(io.crate.testing.SymbolMatchers.isFunction) ArraySliceFunction(io.crate.expression.scalar.ArraySliceFunction) ImplicitCastFunction(io.crate.expression.scalar.cast.ImplicitCastFunction) Function(io.crate.expression.symbol.Function) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) RelationName(io.crate.metadata.RelationName) SessionContext(io.crate.action.sql.SessionContext) TableInfo(io.crate.metadata.table.TableInfo) AliasedAnalyzedRelation(io.crate.analyze.relations.AliasedAnalyzedRelation) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) TableRelation(io.crate.analyze.relations.TableRelation) AliasedAnalyzedRelation(io.crate.analyze.relations.AliasedAnalyzedRelation) ScopedSymbol(io.crate.expression.symbol.ScopedSymbol) FullQualifiedNameFieldProvider(io.crate.analyze.relations.FullQualifiedNameFieldProvider) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 23 with CoordinatorTxnCtx

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

the class UserDefinedFunctionService method validateFunctionIsNotInUseByGeneratedColumn.

void validateFunctionIsNotInUseByGeneratedColumn(String schema, String functionName, UserDefinedFunctionsMetadata functionsMetadata, ClusterState currentState) {
    // The iteration of schemas/tables must happen on the node context WITHOUT the UDF already removed.
    // Otherwise the lazy table factories will already fail while evaluating generated functionsMetadata.
    // To avoid that, a copy of the node context with the removed UDF function is used on concrete expression evaluation.
    var nodeCtxWithRemovedFunction = new NodeContext(nodeCtx.functions().copyOf());
    updateImplementations(schema, functionsMetadata.functionsMetadata().stream(), nodeCtxWithRemovedFunction);
    var metadata = currentState.metadata();
    var indices = Stream.of(metadata.getConcreteAllIndices()).filter(NO_BLOB_NOR_DANGLING).map(IndexParts::new).filter(indexParts -> !indexParts.isPartitioned()).collect(Collectors.toList());
    var templates = metadata.getTemplates().keysIt();
    while (templates.hasNext()) {
        var indexParts = new IndexParts(templates.next());
        if (indexParts.isPartitioned()) {
            indices.add(indexParts);
        }
    }
    var indexNameExpressionResolver = new IndexNameExpressionResolver();
    for (var indexParts : indices) {
        var tableInfo = new DocTableInfoBuilder(nodeCtx, indexParts.toRelationName(), currentState, indexNameExpressionResolver).build();
        TableReferenceResolver tableReferenceResolver = new TableReferenceResolver(tableInfo.columns(), tableInfo.ident());
        CoordinatorTxnCtx coordinatorTxnCtx = CoordinatorTxnCtx.systemTransactionContext();
        ExpressionAnalyzer exprAnalyzer = new ExpressionAnalyzer(coordinatorTxnCtx, nodeCtxWithRemovedFunction, ParamTypeHints.EMPTY, tableReferenceResolver, null);
        for (var ref : tableInfo.columns()) {
            if (ref instanceof GeneratedReference) {
                var genRef = (GeneratedReference) ref;
                Expression expression = SqlParser.createExpression(genRef.formattedGeneratedExpression());
                try {
                    exprAnalyzer.convert(expression, new ExpressionAnalysisContext(coordinatorTxnCtx.sessionContext()));
                } catch (UnsupportedOperationException e) {
                    throw new IllegalArgumentException("Cannot drop function '" + functionName + "', it is still in use by '" + tableInfo + "." + genRef + "'");
                }
            }
        }
    }
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) IndexParts(io.crate.metadata.IndexParts) UserDefinedFunctionAlreadyExistsException(io.crate.exceptions.UserDefinedFunctionAlreadyExistsException) FunctionName(io.crate.metadata.FunctionName) ClusterService(org.elasticsearch.cluster.service.ClusterService) FunctionProvider(io.crate.metadata.FunctionProvider) HashMap(java.util.HashMap) TableReferenceResolver(io.crate.analyze.expressions.TableReferenceResolver) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ClusterState(org.elasticsearch.cluster.ClusterState) Metadata(org.elasticsearch.cluster.metadata.Metadata) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) Locale(java.util.Locale) Map(java.util.Map) SqlParser(io.crate.sql.parser.SqlParser) Nullable(javax.annotation.Nullable) ScriptException(javax.script.ScriptException) NO_BLOB_NOR_DANGLING(io.crate.metadata.doc.DocSchemaInfo.NO_BLOB_NOR_DANGLING) NodeContext(io.crate.metadata.NodeContext) Iterator(java.util.Iterator) GeneratedReference(io.crate.metadata.GeneratedReference) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) DataType(io.crate.types.DataType) Signature(io.crate.metadata.functions.Signature) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Collectors(java.util.stream.Collectors) Lists2(io.crate.common.collections.Lists2) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) UserDefinedFunctionUnknownException(io.crate.exceptions.UserDefinedFunctionUnknownException) FunctionType(io.crate.metadata.FunctionType) Singleton(org.elasticsearch.common.inject.Singleton) TimeValue(io.crate.common.unit.TimeValue) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) Scalar(io.crate.metadata.Scalar) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) LogManager(org.apache.logging.log4j.LogManager) Expression(io.crate.sql.tree.Expression) ActionListener(org.elasticsearch.action.ActionListener) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) DocTableInfoBuilder(io.crate.metadata.doc.DocTableInfoBuilder) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) GeneratedReference(io.crate.metadata.GeneratedReference) NodeContext(io.crate.metadata.NodeContext) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) IndexParts(io.crate.metadata.IndexParts) Expression(io.crate.sql.tree.Expression) DocTableInfoBuilder(io.crate.metadata.doc.DocTableInfoBuilder) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) TableReferenceResolver(io.crate.analyze.expressions.TableReferenceResolver)

Example 24 with CoordinatorTxnCtx

use of io.crate.metadata.CoordinatorTxnCtx 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 25 with CoordinatorTxnCtx

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

the class LogicalPlanner method plan.

public LogicalPlan plan(AnalyzedRelation relation, PlannerContext plannerContext, SubqueryPlanner subqueryPlanner, boolean avoidTopLevelFetch) {
    CoordinatorTxnCtx coordinatorTxnCtx = plannerContext.transactionContext();
    var planBuilder = new PlanBuilder(subqueryPlanner, coordinatorTxnCtx, tableStats, plannerContext.params());
    LogicalPlan logicalPlan = relation.accept(planBuilder, relation.outputs());
    LogicalPlan optimizedPlan = optimizer.optimize(logicalPlan, tableStats, coordinatorTxnCtx);
    assert logicalPlan.outputs().equals(optimizedPlan.outputs()) : "Optimized plan must have the same outputs as original plan";
    LogicalPlan prunedPlan = optimizedPlan.pruneOutputsExcept(tableStats, relation.outputs());
    assert logicalPlan.outputs().equals(optimizedPlan.outputs()) : "Pruned plan must have the same outputs as original plan";
    LogicalPlan fetchOptimized = fetchOptimizer.optimize(prunedPlan, tableStats, coordinatorTxnCtx);
    if (fetchOptimized != prunedPlan || avoidTopLevelFetch) {
        return fetchOptimized;
    }
    assert logicalPlan.outputs().equals(fetchOptimized.outputs()) : "Fetch optimized plan must have the same outputs as original plan";
    // even if there is no operator that reduces the number of records
    return RewriteToQueryThenFetch.tryRewrite(relation, fetchOptimized, tableStats);
}
Also used : CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx)

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