Search in sources :

Example 1 with ExpressionsInput

use of io.crate.expression.ExpressionsInput in project crate by crate.

the class JobsLogService method createFilter.

private ExpressionsInput<JobContextLog, Boolean> createFilter(String filterExpression, String settingName) {
    Symbol filter = asSymbol(filterExpression);
    if (!filter.valueType().equals(DataTypes.BOOLEAN)) {
        throw new IllegalArgumentException("Filter expression for " + settingName + " must result in a boolean, not: " + filter.valueType() + " (`" + filter + "`)");
    }
    InputFactory.Context<NestableCollectExpression<JobContextLog, ?>> ctx = inputFactory.ctxForRefs(systemTransactionCtx, refResolver);
    @SuppressWarnings("unchecked") Input<Boolean> filterInput = (Input<Boolean>) ctx.add(filter);
    return new ExpressionsInput<>(filterInput, ctx.expressions());
}
Also used : InputFactory(io.crate.expression.InputFactory) Input(io.crate.data.Input) ExpressionsInput(io.crate.expression.ExpressionsInput) Symbol(io.crate.expression.symbol.Symbol) NestableCollectExpression(io.crate.execution.engine.collect.NestableCollectExpression) ExpressionsInput(io.crate.expression.ExpressionsInput)

Example 2 with ExpressionsInput

use of io.crate.expression.ExpressionsInput in project crate by crate.

the class WindowProjector method fromProjection.

public static Projector fromProjection(WindowAggProjection projection, NodeContext nodeCtx, InputFactory inputFactory, TransactionContext txnCtx, RamAccounting ramAccounting, MemoryManager memoryManager, Version minNodeVersion, Version indexVersionCreated, IntSupplier numThreads, Executor executor) {
    var windowFunctionSymbols = projection.windowFunctions();
    var numWindowFunctions = windowFunctionSymbols.size();
    assert numWindowFunctions > 0 : "WindowAggProjection must have at least 1 window function.";
    ArrayList<WindowFunction> windowFunctions = new ArrayList<>(numWindowFunctions);
    ArrayList<CollectExpression<Row, ?>> windowFuncArgsExpressions = new ArrayList<>(numWindowFunctions);
    Input[][] windowFuncArgsInputs = new Input[numWindowFunctions][];
    Boolean[] ignoreNulls = new Boolean[numWindowFunctions];
    for (int idx = 0; idx < numWindowFunctions; idx++) {
        var windowFunctionSymbol = windowFunctionSymbols.get(idx);
        InputFactory.Context<CollectExpression<Row, ?>> ctx = inputFactory.ctxForInputColumns(txnCtx);
        ctx.add(windowFunctionSymbol.arguments());
        FunctionImplementation impl = nodeCtx.functions().getQualified(windowFunctionSymbol, txnCtx.sessionSettings().searchPath());
        assert impl != null : "Function implementation not found using full qualified lookup";
        if (impl instanceof AggregationFunction) {
            var filterInputFactoryCtx = inputFactory.ctxForInputColumns(txnCtx);
            var filterSymbol = windowFunctionSymbol.filter();
            // noinspection unchecked
            Input<Boolean> filterInput = filterSymbol == null ? Literal.BOOLEAN_TRUE : (Input<Boolean>) filterInputFactoryCtx.add(filterSymbol);
            ExpressionsInput<Row, Boolean> filter = new ExpressionsInput<>(filterInput, filterInputFactoryCtx.expressions());
            windowFunctions.add(new AggregateToWindowFunctionAdapter((AggregationFunction) impl, filter, indexVersionCreated, ramAccounting, memoryManager, minNodeVersion));
        } else if (impl instanceof WindowFunction) {
            windowFunctions.add((WindowFunction) impl);
        } else {
            throw new AssertionError("Function needs to be either a window or an aggregate function");
        }
        windowFuncArgsExpressions.addAll(ctx.expressions());
        windowFuncArgsInputs[idx] = ctx.topLevelInputs().toArray(new Input[0]);
        ignoreNulls[idx] = windowFunctionSymbol.ignoreNulls();
    }
    var windowDefinition = projection.windowDefinition();
    var partitions = windowDefinition.partitions();
    Supplier<InputFactory.Context<CollectExpression<Row, ?>>> createInputFactoryContext = () -> inputFactory.ctxForInputColumns(txnCtx);
    int arrayListElementOverHead = 32;
    RowAccountingWithEstimators accounting = new RowAccountingWithEstimators(Symbols.typeView(projection.standalone()), ramAccounting, arrayListElementOverHead);
    Comparator<Object[]> cmpPartitionBy = partitions.isEmpty() ? null : createComparator(createInputFactoryContext, new OrderBy(windowDefinition.partitions()));
    Comparator<Object[]> cmpOrderBy = createComparator(createInputFactoryContext, windowDefinition.orderBy());
    int numCellsInSourceRow = projection.standalone().size();
    ComputeFrameBoundary<Object[]> computeFrameStart = createComputeStartFrameBoundary(numCellsInSourceRow, txnCtx, nodeCtx, windowDefinition, cmpOrderBy);
    ComputeFrameBoundary<Object[]> computeFrameEnd = createComputeEndFrameBoundary(numCellsInSourceRow, txnCtx, nodeCtx, windowDefinition, cmpOrderBy);
    return sourceRows -> WindowFunctionBatchIterator.of(sourceRows, accounting, computeFrameStart, computeFrameEnd, cmpPartitionBy, cmpOrderBy, numCellsInSourceRow, numThreads, executor, windowFunctions, windowFuncArgsExpressions, ignoreNulls, windowFuncArgsInputs);
}
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) InputFactory(io.crate.expression.InputFactory) ArrayList(java.util.ArrayList) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) Input(io.crate.data.Input) ExpressionsInput(io.crate.expression.ExpressionsInput) RowAccountingWithEstimators(io.crate.breaker.RowAccountingWithEstimators) FunctionImplementation(io.crate.metadata.FunctionImplementation) TransactionContext(io.crate.metadata.TransactionContext) NodeContext(io.crate.metadata.NodeContext) OrderBy(io.crate.analyze.OrderBy) CollectExpression(io.crate.execution.engine.collect.CollectExpression) Row(io.crate.data.Row) ExpressionsInput(io.crate.expression.ExpressionsInput)

Example 3 with ExpressionsInput

use of io.crate.expression.ExpressionsInput in project crate by crate.

the class AbstractWindowFunctionTest method assertEvaluate.

@SuppressWarnings("unchecked")
protected <T> void assertEvaluate(String functionExpression, Matcher<T> expectedValue, List<ColumnIdent> rowsColumnDescription, Object[]... inputRows) throws Throwable {
    performInputSanityChecks(inputRows);
    Symbol normalizedFunctionSymbol = sqlExpressions.normalize(sqlExpressions.asSymbol(functionExpression));
    assertThat(normalizedFunctionSymbol, instanceOf(io.crate.expression.symbol.WindowFunction.class));
    var windowFunctionSymbol = (io.crate.expression.symbol.WindowFunction) normalizedFunctionSymbol;
    ReferenceResolver<InputCollectExpression> referenceResolver = r -> new InputCollectExpression(rowsColumnDescription.indexOf(r.column()));
    var sourceSymbols = Lists2.map(rowsColumnDescription, x -> sqlExpressions.normalize(sqlExpressions.asSymbol(x.sqlFqn())));
    ensureInputRowsHaveCorrectType(sourceSymbols, inputRows);
    var argsCtx = inputFactory.ctxForRefs(txnCtx, referenceResolver);
    argsCtx.add(windowFunctionSymbol.arguments());
    FunctionImplementation impl = sqlExpressions.nodeCtx.functions().getQualified(windowFunctionSymbol, txnCtx.sessionSettings().searchPath());
    assert impl instanceof WindowFunction || impl instanceof AggregationFunction : "Got " + impl + " but expected a window function";
    WindowFunction windowFunctionImpl;
    if (impl instanceof AggregationFunction) {
        windowFunctionImpl = new AggregateToWindowFunctionAdapter((AggregationFunction) impl, new ExpressionsInput<>(Literal.BOOLEAN_TRUE, List.of()), Version.CURRENT, RamAccounting.NO_ACCOUNTING, memoryManager, Version.CURRENT);
    } else {
        windowFunctionImpl = (WindowFunction) impl;
    }
    int numCellsInSourceRows = inputRows[0].length;
    var windowDef = windowFunctionSymbol.windowDefinition();
    var partitionOrderBy = windowDef.partitions().isEmpty() ? null : new OrderBy(windowDef.partitions());
    Comparator<Object[]> cmpOrderBy = createComparator(() -> inputFactory.ctxForRefs(txnCtx, referenceResolver), windowDef.orderBy());
    InputColumns.SourceSymbols inputColSources = new InputColumns.SourceSymbols(sourceSymbols);
    var mappedWindowDef = windowDef.map(s -> InputColumns.create(s, inputColSources));
    BatchIterator<Row> iterator = WindowFunctionBatchIterator.of(InMemoryBatchIterator.of(Arrays.stream(inputRows).map(RowN::new).collect(Collectors.toList()), SENTINEL, true), new IgnoreRowAccounting(), WindowProjector.createComputeStartFrameBoundary(numCellsInSourceRows, txnCtx, sqlExpressions.nodeCtx, mappedWindowDef, cmpOrderBy), WindowProjector.createComputeEndFrameBoundary(numCellsInSourceRows, txnCtx, sqlExpressions.nodeCtx, mappedWindowDef, cmpOrderBy), createComparator(() -> inputFactory.ctxForRefs(txnCtx, referenceResolver), partitionOrderBy), cmpOrderBy, numCellsInSourceRows, () -> 1, Runnable::run, List.of(windowFunctionImpl), argsCtx.expressions(), new Boolean[] { windowFunctionSymbol.ignoreNulls() }, argsCtx.topLevelInputs().toArray(new Input[0]));
    List<Object> actualResult;
    try {
        actualResult = BatchIterators.collect(iterator, Collectors.mapping(row -> row.get(numCellsInSourceRows), Collectors.toList())).get(5, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
        throw e.getCause();
    }
    assertThat((T) actualResult, expectedValue);
}
Also used : Input(io.crate.data.Input) TransactionContext(io.crate.metadata.TransactionContext) SqlExpressions(io.crate.testing.SqlExpressions) Arrays(java.util.Arrays) Array(java.lang.reflect.Array) RelationName(io.crate.metadata.RelationName) SENTINEL(io.crate.data.SentinelRow.SENTINEL) BatchIterator(io.crate.data.BatchIterator) ReferenceResolver(io.crate.expression.reference.ReferenceResolver) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) RowN(io.crate.data.RowN) Map(java.util.Map) SQLExecutor(io.crate.testing.SQLExecutor) Before(org.junit.Before) DocTableInfo(io.crate.metadata.doc.DocTableInfo) User(io.crate.user.User) AbstractModule(org.elasticsearch.common.inject.AbstractModule) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) ColumnIdent(io.crate.metadata.ColumnIdent) Comparators.createComparator(io.crate.execution.engine.sort.Comparators.createComparator) RamAccounting(io.crate.breaker.RamAccounting) Collectors(java.util.stream.Collectors) Lists2(io.crate.common.collections.Lists2) InputCollectExpression(io.crate.execution.engine.collect.InputCollectExpression) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ExpressionsInput(io.crate.expression.ExpressionsInput) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) BatchIterators(io.crate.data.BatchIterators) Version(org.elasticsearch.Version) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) Matcher(org.hamcrest.Matcher) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) InputColumns(io.crate.execution.dsl.projection.builder.InputColumns) OnHeapMemoryManager(io.crate.memory.OnHeapMemoryManager) InputFactory(io.crate.expression.InputFactory) Comparator(java.util.Comparator) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Symbol(io.crate.expression.symbol.Symbol) AggregationFunction(io.crate.execution.engine.aggregation.AggregationFunction) Input(io.crate.data.Input) ExpressionsInput(io.crate.expression.ExpressionsInput) InputCollectExpression(io.crate.execution.engine.collect.InputCollectExpression) FunctionImplementation(io.crate.metadata.FunctionImplementation) ExecutionException(java.util.concurrent.ExecutionException) OrderBy(io.crate.analyze.OrderBy) InputColumns(io.crate.execution.dsl.projection.builder.InputColumns) Row(io.crate.data.Row) ExpressionsInput(io.crate.expression.ExpressionsInput)

Aggregations

Input (io.crate.data.Input)3 ExpressionsInput (io.crate.expression.ExpressionsInput)3 InputFactory (io.crate.expression.InputFactory)3 Symbol (io.crate.expression.symbol.Symbol)3 OrderBy (io.crate.analyze.OrderBy)2 RamAccounting (io.crate.breaker.RamAccounting)2 Row (io.crate.data.Row)2 AggregationFunction (io.crate.execution.engine.aggregation.AggregationFunction)2 Comparators.createComparator (io.crate.execution.engine.sort.Comparators.createComparator)2 Literal (io.crate.expression.symbol.Literal)2 FunctionImplementation (io.crate.metadata.FunctionImplementation)2 TransactionContext (io.crate.metadata.TransactionContext)2 Comparator (java.util.Comparator)2 List (java.util.List)2 Version (org.elasticsearch.Version)2 SymbolEvaluator.evaluateWithoutParams (io.crate.analyze.SymbolEvaluator.evaluateWithoutParams)1 WindowDefinition (io.crate.analyze.WindowDefinition)1 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)1 DocTableRelation (io.crate.analyze.relations.DocTableRelation)1 RowAccountingWithEstimators (io.crate.breaker.RowAccountingWithEstimators)1