Search in sources :

Example 21 with BatchIterator

use of io.crate.data.BatchIterator in project crate by crate.

the class BatchPagingIteratorTest method testBatchPagingIteratorWithPagedSource.

@Test
public void testBatchPagingIteratorWithPagedSource() throws Exception {
    List<Object[]> expectedResult = StreamSupport.stream(RowGenerator.range(0, 10).spliterator(), false).map(Row::materialize).collect(Collectors.toList());
    Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> {
        BatchSimulatingIterator<Row> source = new BatchSimulatingIterator<>(TestingBatchIterators.range(0, 10), 2, 5, executor);
        Function<Integer, KillableCompletionStage<? extends Iterable<? extends KeyIterable<Integer, Row>>>> fetchMore = exhausted -> {
            List<Row> rows = new ArrayList<>();
            while (source.moveNext()) {
                rows.add(new RowN(source.currentElement().materialize()));
            }
            if (source.allLoaded()) {
                return KillableCompletionStage.whenKilled(CompletableFuture.completedFuture(singletonList(new KeyIterable<>(1, rows))), t -> {
                });
            }
            // but to simulate multiple pages and fetchMore calls
            try {
                return KillableCompletionStage.whenKilled(source.loadNextBatch().toCompletableFuture().thenApply(ignored -> {
                    while (source.moveNext()) {
                        rows.add(new RowN(source.currentElement().materialize()));
                    }
                    return singleton(new KeyIterable<>(1, rows));
                }), t -> {
                });
            } catch (Exception e) {
                return KillableCompletionStage.failed(e);
            }
        };
        return new BatchPagingIterator<>(PassThroughPagingIterator.repeatable(), fetchMore, source::allLoaded, throwable -> {
            if (throwable == null) {
                source.close();
            } else {
                source.kill(throwable);
            }
        });
    };
    BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier);
    tester.verifyResultAndEdgeCaseBehaviour(expectedResult);
}
Also used : BatchIterator(io.crate.data.BatchIterator) BatchSimulatingIterator(io.crate.testing.BatchSimulatingIterator) CompletableFuture(java.util.concurrent.CompletableFuture) BatchIteratorTester(io.crate.testing.BatchIteratorTester) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) RowN(io.crate.data.RowN) Collections.singleton(java.util.Collections.singleton) After(org.junit.After) StreamSupport(java.util.stream.StreamSupport) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) KillableCompletionStage(io.crate.concurrent.KillableCompletionStage) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) RowGenerator(io.crate.testing.RowGenerator) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TestingBatchIterators(io.crate.testing.TestingBatchIterators) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Row(io.crate.data.Row) ArrayList(java.util.ArrayList) BatchIterator(io.crate.data.BatchIterator) Function(java.util.function.Function) RowN(io.crate.data.RowN) BatchSimulatingIterator(io.crate.testing.BatchSimulatingIterator) BatchIteratorTester(io.crate.testing.BatchIteratorTester) Row(io.crate.data.Row) Test(org.junit.Test)

Example 22 with BatchIterator

use of io.crate.data.BatchIterator in project crate by crate.

the class NodeStatsTest method testNoRequestIfNotRequired.

@Test
public void testNoRequestIfNotRequired() throws Exception {
    List<Symbol> toCollect = new ArrayList<>();
    toCollect.add(idRef);
    when(collectPhase.toCollect()).thenReturn(toCollect);
    BatchIterator iterator = NodeStats.newInstance(transportNodeStatsAction, collectPhase, nodes, txnCtx, new InputFactory(nodeCtx));
    iterator.loadNextBatch();
    // Because only id and name are selected, transportNodesStatsAction should be never used
    verifyNoMoreInteractions(transportNodeStatsAction);
}
Also used : InputFactory(io.crate.expression.InputFactory) Symbol(io.crate.expression.symbol.Symbol) ArrayList(java.util.ArrayList) BatchIterator(io.crate.data.BatchIterator) Test(org.junit.Test)

Example 23 with BatchIterator

use of io.crate.data.BatchIterator in project crate by crate.

the class NodeStatsTest method testRequestsAreIssued.

@Test
public void testRequestsAreIssued() throws Exception {
    List<Symbol> toCollect = new ArrayList<>();
    toCollect.add(idRef);
    toCollect.add(nameRef);
    when(collectPhase.toCollect()).thenReturn(toCollect);
    BatchIterator iterator = NodeStats.newInstance(transportNodeStatsAction, collectPhase, nodes, txnCtx, new InputFactory(nodeCtx));
    iterator.loadNextBatch();
    verifyNoMoreInteractions(transportNodeStatsAction);
}
Also used : InputFactory(io.crate.expression.InputFactory) Symbol(io.crate.expression.symbol.Symbol) ArrayList(java.util.ArrayList) BatchIterator(io.crate.data.BatchIterator) Test(org.junit.Test)

Example 24 with BatchIterator

use of io.crate.data.BatchIterator 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)

Example 25 with BatchIterator

use of io.crate.data.BatchIterator in project crate by crate.

the class FileCollectSource method getCollector.

@Override
public CrateCollector getCollector(CollectPhase collectPhase, BatchConsumer consumer, JobCollectContext jobCollectContext) {
    FileUriCollectPhase fileUriCollectPhase = (FileUriCollectPhase) collectPhase;
    InputFactory.Context<LineCollectorExpression<?>> ctx = inputFactory.ctxForRefs(FileLineReferenceResolver::getImplementation);
    ctx.add(collectPhase.toCollect());
    String[] readers = fileUriCollectPhase.nodeIds().toArray(new String[fileUriCollectPhase.nodeIds().size()]);
    Arrays.sort(readers);
    List<String> fileUris;
    fileUris = targetUriToStringList(fileUriCollectPhase.targetUri());
    BatchIterator fileReadingIterator = FileReadingIterator.newInstance(fileUris, ctx.topLevelInputs(), ctx.expressions(), fileUriCollectPhase.compression(), fileInputFactoryMap, fileUriCollectPhase.sharedStorage(), readers.length, Arrays.binarySearch(readers, clusterService.state().nodes().getLocalNodeId()));
    return BatchIteratorCollectorBridge.newInstance(fileReadingIterator, consumer);
}
Also used : FileInputFactory(io.crate.operation.collect.files.FileInputFactory) InputFactory(io.crate.operation.InputFactory) LineCollectorExpression(io.crate.operation.collect.files.LineCollectorExpression) FileLineReferenceResolver(io.crate.operation.reference.file.FileLineReferenceResolver) BatchIterator(io.crate.data.BatchIterator) FileUriCollectPhase(io.crate.planner.node.dql.FileUriCollectPhase)

Aggregations

BatchIterator (io.crate.data.BatchIterator)50 Test (org.junit.Test)37 BatchIteratorTester (io.crate.testing.BatchIteratorTester)22 InMemoryBatchIterator (io.crate.data.InMemoryBatchIterator)17 Row (io.crate.data.Row)16 ArrayList (java.util.ArrayList)10 CrateUnitTest (io.crate.test.integration.CrateUnitTest)8 List (java.util.List)8 Map (java.util.Map)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 Bucket (io.crate.data.Bucket)6 InputFactory (io.crate.expression.InputFactory)6 Symbol (io.crate.analyze.symbol.Symbol)4 RowAccounting (io.crate.breaker.RowAccounting)4 RowN (io.crate.data.RowN)4 CombinedRow (io.crate.data.join.CombinedRow)4 InputFactory (io.crate.operation.InputFactory)4 TestingHelpers.isRow (io.crate.testing.TestingHelpers.isRow)4 UUID (java.util.UUID)4 ClusterService (org.elasticsearch.cluster.service.ClusterService)4