Search in sources :

Example 16 with NodeContext

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

the class WindowProjector method createComputeEndFrameBoundary.

static ComputeFrameBoundary<Object[]> createComputeEndFrameBoundary(int numCellsInSourceRow, TransactionContext txnCtx, NodeContext nodeCtx, WindowDefinition windowDefinition, Comparator<Object[]> cmpOrderBy) {
    var frameDefinition = windowDefinition.windowFrameDefinition();
    var frameBoundEnd = frameDefinition.end();
    var framingMode = frameDefinition.mode();
    DataType offsetType = frameBoundEnd.value().valueType();
    Object offsetValue = evaluateWithoutParams(txnCtx, nodeCtx, frameBoundEnd.value());
    Object[] endProbeValues = new Object[numCellsInSourceRow];
    BiFunction<Object[], Object[], Object[]> updateProbeValues;
    if (offsetValue != null && framingMode == WindowFrame.Mode.RANGE) {
        updateProbeValues = createUpdateProbeValueFunction(windowDefinition, ArithmeticOperatorsFactory::getAddFunction, offsetValue, offsetType);
    } else {
        updateProbeValues = (currentRow, x) -> x;
    }
    return (partitionStart, partitionEnd, currentIndex, sortedRows) -> frameBoundEnd.type().getEnd(framingMode, partitionStart, partitionEnd, currentIndex, offsetValue, updateProbeValues.apply(sortedRows.get(currentIndex), endProbeValues), cmpOrderBy, sortedRows);
}
Also used : Input(io.crate.data.Input) TransactionContext(io.crate.metadata.TransactionContext) InputColumn(io.crate.expression.symbol.InputColumn) WindowFrame(io.crate.sql.tree.WindowFrame) BiFunction(java.util.function.BiFunction) RowAccountingWithEstimators(io.crate.breaker.RowAccountingWithEstimators) CollectExpression(io.crate.execution.engine.collect.CollectExpression) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Projector(io.crate.data.Projector) IntervalType(io.crate.types.IntervalType) Symbols(io.crate.expression.symbol.Symbols) Nullable(javax.annotation.Nullable) IntSupplier(java.util.function.IntSupplier) NodeContext(io.crate.metadata.NodeContext) Executor(java.util.concurrent.Executor) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) SymbolType(io.crate.expression.symbol.SymbolType) Comparators.createComparator(io.crate.execution.engine.sort.Comparators.createComparator) DataType(io.crate.types.DataType) SymbolEvaluator.evaluateWithoutParams(io.crate.analyze.SymbolEvaluator.evaluateWithoutParams) MemoryManager(io.crate.memory.MemoryManager) RamAccounting(io.crate.breaker.RamAccounting) ExpressionsInput(io.crate.expression.ExpressionsInput) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) Version(org.elasticsearch.Version) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) WindowDefinition(io.crate.analyze.WindowDefinition) WindowAggProjection(io.crate.execution.dsl.projection.WindowAggProjection) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) InputFactory(io.crate.expression.InputFactory) Comparator(java.util.Comparator) DataType(io.crate.types.DataType)

Example 17 with NodeContext

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

the class WindowProjector method createComputeStartFrameBoundary.

static ComputeFrameBoundary<Object[]> createComputeStartFrameBoundary(int numCellsInSourceRow, TransactionContext txnCtx, NodeContext nodeCtx, WindowDefinition windowDefinition, @Nullable Comparator<Object[]> cmpOrderBy) {
    var frameDefinition = windowDefinition.windowFrameDefinition();
    var frameBoundStart = frameDefinition.start();
    var framingMode = frameDefinition.mode();
    DataType offsetType = frameBoundStart.value().valueType();
    Object offsetValue = evaluateWithoutParams(txnCtx, nodeCtx, frameBoundStart.value());
    Object[] startProbeValues = new Object[numCellsInSourceRow];
    BiFunction<Object[], Object[], Object[]> updateStartProbeValue;
    if (offsetValue != null && framingMode == WindowFrame.Mode.RANGE) {
        updateStartProbeValue = createUpdateProbeValueFunction(windowDefinition, ArithmeticOperatorsFactory::getSubtractFunction, offsetValue, offsetType);
    } else {
        updateStartProbeValue = (currentRow, x) -> x;
    }
    return (partitionStart, partitionEnd, currentIndex, sortedRows) -> frameBoundStart.type().getStart(framingMode, partitionStart, partitionEnd, currentIndex, offsetValue, updateStartProbeValue.apply(sortedRows.get(currentIndex), startProbeValues), cmpOrderBy, sortedRows);
}
Also used : Input(io.crate.data.Input) TransactionContext(io.crate.metadata.TransactionContext) InputColumn(io.crate.expression.symbol.InputColumn) WindowFrame(io.crate.sql.tree.WindowFrame) BiFunction(java.util.function.BiFunction) RowAccountingWithEstimators(io.crate.breaker.RowAccountingWithEstimators) CollectExpression(io.crate.execution.engine.collect.CollectExpression) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Projector(io.crate.data.Projector) IntervalType(io.crate.types.IntervalType) Symbols(io.crate.expression.symbol.Symbols) Nullable(javax.annotation.Nullable) IntSupplier(java.util.function.IntSupplier) NodeContext(io.crate.metadata.NodeContext) Executor(java.util.concurrent.Executor) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) SymbolType(io.crate.expression.symbol.SymbolType) Comparators.createComparator(io.crate.execution.engine.sort.Comparators.createComparator) DataType(io.crate.types.DataType) SymbolEvaluator.evaluateWithoutParams(io.crate.analyze.SymbolEvaluator.evaluateWithoutParams) MemoryManager(io.crate.memory.MemoryManager) RamAccounting(io.crate.breaker.RamAccounting) ExpressionsInput(io.crate.expression.ExpressionsInput) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) Version(org.elasticsearch.Version) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) WindowDefinition(io.crate.analyze.WindowDefinition) WindowAggProjection(io.crate.execution.dsl.projection.WindowAggProjection) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) InputFactory(io.crate.expression.InputFactory) Comparator(java.util.Comparator) DataType(io.crate.types.DataType)

Example 18 with NodeContext

use of io.crate.metadata.NodeContext 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 19 with NodeContext

use of io.crate.metadata.NodeContext 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 20 with NodeContext

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

the class GroupByOptimizedIteratorTest method prepare.

@Before
public void prepare() throws Exception {
    NodeContext nodeCtx = createNodeContext();
    IndexWriter iw = new IndexWriter(new ByteBuffersDirectory(), new IndexWriterConfig(new StandardAnalyzer()));
    columnName = "x";
    expectedResult = new ArrayList<>(20);
    for (long i = 0; i < 20; i++) {
        Document doc = new Document();
        String val = "val_" + i;
        doc.add(new SortedSetDocValuesField(columnName, new BytesRef(val)));
        iw.addDocument(doc);
        expectedResult.add(new Object[] { val, 1L });
    }
    iw.commit();
    indexSearcher = new IndexSearcher(DirectoryReader.open(iw));
    inExpr = new InputCollectExpression(0);
    CountAggregation aggregation = (CountAggregation) nodeCtx.functions().getQualified(CountAggregation.COUNT_STAR_SIGNATURE, Collections.emptyList(), CountAggregation.COUNT_STAR_SIGNATURE.getReturnType().createType());
    aggregationContexts = List.of(new AggregationContext(aggregation, () -> true, List.of()));
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) AggregationContext(io.crate.execution.engine.aggregation.AggregationContext) TestingHelpers.createNodeContext(io.crate.testing.TestingHelpers.createNodeContext) NodeContext(io.crate.metadata.NodeContext) Document(org.apache.lucene.document.Document) IndexWriter(org.apache.lucene.index.IndexWriter) ByteBuffersDirectory(org.apache.lucene.store.ByteBuffersDirectory) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) CountAggregation(io.crate.execution.engine.aggregation.impl.CountAggregation) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) BytesRef(org.apache.lucene.util.BytesRef) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) Before(org.junit.Before)

Aggregations

NodeContext (io.crate.metadata.NodeContext)29 Symbol (io.crate.expression.symbol.Symbol)16 Row (io.crate.data.Row)14 CoordinatorTxnCtx (io.crate.metadata.CoordinatorTxnCtx)12 List (java.util.List)12 SymbolEvaluator (io.crate.analyze.SymbolEvaluator)10 VisibleForTesting (io.crate.common.annotations.VisibleForTesting)10 Plan (io.crate.planner.Plan)10 PlannerContext (io.crate.planner.PlannerContext)10 SubQueryResults (io.crate.planner.operators.SubQueryResults)10 Function (java.util.function.Function)10 Nullable (javax.annotation.Nullable)10 RowConsumer (io.crate.data.RowConsumer)9 TransactionContext (io.crate.metadata.TransactionContext)9 DependencyCarrier (io.crate.planner.DependencyCarrier)9 ArrayList (java.util.ArrayList)9 Settings (org.elasticsearch.common.settings.Settings)9 Row1 (io.crate.data.Row1)8 OneRowActionListener (io.crate.execution.support.OneRowActionListener)8 Map (java.util.Map)7