Search in sources :

Example 1 with QueryResults

use of io.prestosql.client.QueryResults in project hetu-core by openlookeng.

the class CubeQuery method resultsCubeInitialQuery.

private boolean resultsCubeInitialQuery(Terminal terminal, PrintStream out, PrintStream errorChannel, ClientOptions.OutputFormat outputFormat, boolean usePager, boolean showProgress) {
    StatusPrinter statusPrinter = null;
    WarningsPrinter warningsPrinter = new PrintStreamWarningsPrinter(errorChannel);
    if (showProgress) {
        statusPrinter = new StatusPrinter(client, errorChannel, debug);
        statusPrinter.printInitialStatusUpdates(terminal);
    } else {
        processInitialStatusUpdates(warningsPrinter);
    }
    // if running or finished
    if (client.isRunning() || (client.isFinished() && client.finalStatusInfo().getError() == null)) {
        QueryStatusInfo results = client.isRunning() ? client.currentStatusInfo() : client.finalStatusInfo();
        if (results.getUpdateType() != null) {
            renderUpdate(errorChannel, results);
        } else if (results.getColumns() == null) {
            errorChannel.printf("Query %s has no columns\n", results.getId());
            return false;
        } else {
            renderResults(out, outputFormat, usePager, results.getColumns());
            // /populate results from here
            if (cubeConsole.getListRowBufferIterationItems().size() == EMPTY_ITERATION_LIST_SIZE) {
                if (client.isFinished() && client.finalStatusInfo().getError() == null) {
                    QueryData queryData = ((QueryResults) results);
                    if (queryData.getData() != null) {
                        if (queryData.getData().iterator().hasNext()) {
                            if (queryData.getData().iterator().next().iterator().hasNext()) {
                                cubeInitQueryResult = queryData.getData().iterator().next().iterator().next().toString();
                            }
                        }
                    }
                }
            }
        }
    }
    checkState(!client.isRunning());
    warningsPrinter.print(client.finalStatusInfo().getWarnings(), true, true);
    if (showProgress) {
        statusPrinter.printFinalInfo();
    }
    if (client.isClientAborted()) {
        errorChannel.println("Query aborted by user");
        return false;
    }
    if (client.isClientError()) {
        errorChannel.println("Query is gone (server restarted?)");
        return false;
    }
    verify(client.isFinished());
    if (client.finalStatusInfo().getError() != null) {
        renderFailure(errorChannel);
        return false;
    }
    return true;
}
Also used : QueryData(io.prestosql.client.QueryData) QueryStatusInfo(io.prestosql.client.QueryStatusInfo) QueryResults(io.prestosql.client.QueryResults)

Example 2 with QueryResults

use of io.prestosql.client.QueryResults in project hetu-core by openlookeng.

the class TestQueryStateInfoResource method setup.

@BeforeClass
public void setup() {
    Request request1 = preparePost().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()).setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)).setHeader(PRESTO_USER, "user1").build();
    queryResults = client.execute(request1, createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
    client.execute(prepareGet().setUri(queryResults.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
    Request request2 = preparePost().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build()).setBodyGenerator(createStaticBodyGenerator(LONG_LASTING_QUERY, UTF_8)).setHeader(PRESTO_USER, "user2").build();
    QueryResults queryResults2 = client.execute(request2, createJsonResponseHandler(jsonCodec(QueryResults.class)));
    client.execute(prepareGet().setUri(queryResults2.getNextUri()).build(), createJsonResponseHandler(QUERY_RESULTS_JSON_CODEC));
    // queries are started in the background, so they may not all be immediately visible
    while (true) {
        List<BasicQueryInfo> queryInfos1 = client.execute(prepareGet().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/query").build()).setHeader(PRESTO_USER, "user1").build(), createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class)));
        List<BasicQueryInfo> queryInfos2 = client.execute(prepareGet().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/query").build()).setHeader(PRESTO_USER, "user2").build(), createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class)));
        if ((queryInfos1.size() == 1) && queryInfos1.stream().allMatch(info -> info.getState() == RUNNING) && (queryInfos2.size() == 1) && queryInfos2.stream().allMatch(info -> info.getState() == RUNNING)) {
            break;
        }
    }
}
Also used : HttpClient(io.airlift.http.client.HttpClient) Test(org.testng.annotations.Test) PRESTO_USER(io.prestosql.client.PrestoHeaders.PRESTO_USER) UnexpectedResponseException(io.airlift.http.client.UnexpectedResponseException) Assert.assertEquals(io.prestosql.testing.assertions.Assert.assertEquals) Request(io.airlift.http.client.Request) RUNNING(io.prestosql.execution.QueryState.RUNNING) AfterClass(org.testng.annotations.AfterClass) Builder.preparePost(io.airlift.http.client.Request.Builder.preparePost) Builder.prepareGet(io.airlift.http.client.Request.Builder.prepareGet) JettyHttpClient(io.airlift.http.client.jetty.JettyHttpClient) QueryResults(io.prestosql.client.QueryResults) Closeables.closeQuietly(io.airlift.testing.Closeables.closeQuietly) UTF_8(java.nio.charset.StandardCharsets.UTF_8) BeforeClass(org.testng.annotations.BeforeClass) TestingPrestoServer(io.prestosql.server.testing.TestingPrestoServer) Assert.assertNotNull(org.testng.Assert.assertNotNull) JsonCodec.jsonCodec(io.airlift.json.JsonCodec.jsonCodec) List(java.util.List) JsonCodec.listJsonCodec(io.airlift.json.JsonCodec.listJsonCodec) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JsonResponseHandler.createJsonResponseHandler(io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler) Assert.assertTrue(org.testng.Assert.assertTrue) StaticBodyGenerator.createStaticBodyGenerator(io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator) JsonCodec(io.airlift.json.JsonCodec) TpchPlugin(io.prestosql.plugin.tpch.TpchPlugin) Request(io.airlift.http.client.Request) QueryResults(io.prestosql.client.QueryResults) BeforeClass(org.testng.annotations.BeforeClass)

Example 3 with QueryResults

use of io.prestosql.client.QueryResults in project hetu-core by openlookeng.

the class Query method getNextResult.

private synchronized QueryResults getNextResult(long token, UriInfo uriInfo, String scheme, DataSize targetResultSize) {
    // check if the result for the token have already been created
    Optional<QueryResults> cachedResult = getCachedResult(token);
    if (cachedResult.isPresent()) {
        return cachedResult.get();
    }
    verify(nextToken.isPresent(), "Can not generate next result when next token is not present");
    verify(token == nextToken.getAsLong(), "Expected token to equal next token");
    URI queryHtmlUri = uriInfo.getRequestUriBuilder().scheme(scheme).replacePath("ui/query.html").replaceQuery(queryId.toString()).build();
    // Remove as many pages as possible from the exchange until just greater than DESIRED_RESULT_BYTES
    // NOTE: it is critical that query results are created for the pages removed from the exchange
    // client while holding the lock because the query may transition to the finished state when the
    // last page is removed.  If another thread observes this state before the response is cached
    // the pages will be lost.
    Iterable<List<Object>> data = null;
    try {
        ImmutableList.Builder<RowIterable> pages = ImmutableList.builder();
        long bytes = 0;
        long rows = 0;
        long targetResultBytes = targetResultSize.toBytes();
        while (bytes < targetResultBytes) {
            // at this point, origin is irrelevant, so we can safely ignore it
            SerializedPage serializedPage = exchangeClient.pollPage(null).getLeft();
            if (serializedPage == null) {
                break;
            }
            Page page = serde.deserialize(serializedPage);
            bytes += page.getLogicalSizeInBytes();
            rows += page.getPositionCount();
            pages.add(new RowIterable(session.toConnectorSession(), types, page));
        }
        if (rows > 0) {
            // client implementations do not properly handle empty list of data
            data = Iterables.concat(pages.build());
        }
    } catch (Throwable cause) {
        queryManager.failQuery(queryId, cause);
    }
    // get the query info before returning
    // force update if query manager is closed
    QueryInfo queryInfo = queryManager.getFullQueryInfo(queryId);
    queryManager.recordHeartbeat(queryId);
    // grab the update count for non-queries
    if ((data != null) && (queryInfo.getUpdateType() != null) && (updateCount == null) && (columns.size() == 1) && (columns.get(0).getType().equals(StandardTypes.BIGINT))) {
        Iterator<List<Object>> iterator = data.iterator();
        if (iterator.hasNext()) {
            Number number = (Number) iterator.next().get(0);
            if (number != null) {
                updateCount = number.longValue();
            }
        }
    }
    closeExchangeClientIfNecessary(queryInfo);
    // for queries with no output, return a fake result for clients that require it
    if ((queryInfo.getState() == QueryState.FINISHED) && !queryInfo.getOutputStage().isPresent()) {
        columns = ImmutableList.of(createColumn("result", BooleanType.BOOLEAN));
        data = ImmutableSet.of(ImmutableList.of(true));
    } else if (queryInfo.isRunningAsync()) {
        columns = ImmutableList.of(createColumn("result", BooleanType.BOOLEAN), createColumn("runningAsync", BooleanType.BOOLEAN));
        data = ImmutableSet.of(ImmutableList.of(true, true));
    }
    // (3) Query supports and started running Async
    if ((!queryInfo.isFinalQueryInfo() && queryInfo.getState() != FAILED && !queryInfo.isRunningAsync()) || !exchangeClient.isClosed()) {
        nextToken = OptionalLong.of(token + 1);
    } else {
        nextToken = OptionalLong.empty();
        queryManager.checkForQueryPruning(queryId, queryInfo);
    }
    URI nextResultsUri = null;
    if (nextToken.isPresent()) {
        nextResultsUri = createNextResultsUri(scheme, uriInfo, nextToken.getAsLong());
    }
    // update catalog, schema, and path
    setCatalog = queryInfo.getSetCatalog();
    setSchema = queryInfo.getSetSchema();
    setPath = queryInfo.getSetPath();
    // update setSessionProperties
    setSessionProperties = queryInfo.getSetSessionProperties();
    resetSessionProperties = queryInfo.getResetSessionProperties();
    // update setRoles
    setRoles = queryInfo.getSetRoles();
    // update preparedStatements
    addedPreparedStatements = queryInfo.getAddedPreparedStatements();
    deallocatedPreparedStatements = queryInfo.getDeallocatedPreparedStatements();
    // update startedTransactionId
    startedTransactionId = queryInfo.getStartedTransactionId();
    clearTransactionId = queryInfo.isClearTransactionId();
    // first time through, self is null
    QueryResults queryResults = new QueryResults(queryId.toString(), queryHtmlUri, findCancelableLeafStage(queryInfo), nextResultsUri, columns, data, toStatementStats(queryInfo), toQueryError(queryInfo), mappedCopy(queryInfo.getWarnings(), Query::toClientWarning), queryInfo.getUpdateType(), (queryInfo.isRunningAsync() ? null : updateCount));
    // cache the new result
    lastToken = token;
    lastResult = queryResults;
    return queryResults;
}
Also used : ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) SerializedPage(io.hetu.core.transport.execution.buffer.SerializedPage) Page(io.prestosql.spi.Page) QueryInfo(io.prestosql.execution.QueryInfo) URI(java.net.URI) QueryResults(io.prestosql.client.QueryResults) DataCenterQueryResults(io.prestosql.client.DataCenterQueryResults) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) SerializedPage(io.hetu.core.transport.execution.buffer.SerializedPage)

Example 4 with QueryResults

use of io.prestosql.client.QueryResults in project hetu-core by openlookeng.

the class ExecutingStatementResource method asyncQueryResults.

private void asyncQueryResults(Query query, long token, Duration maxWait, DataSize targetResultSize, UriInfo uriInfo, String scheme, AsyncResponse asyncResponse) {
    Duration wait = WAIT_ORDERING.min(MAX_WAIT_TIME, maxWait);
    DataSize tmpTargetResultSize = targetResultSize == null ? DEFAULT_TARGET_RESULT_SIZE : Ordering.natural().min(targetResultSize, MAX_TARGET_RESULT_SIZE);
    ListenableFuture<QueryResults> queryResultsFuture = query.waitForResults(token, uriInfo, scheme, wait, tmpTargetResultSize);
    ListenableFuture<Response> response = Futures.transform(queryResultsFuture, queryResults -> toResponse(query, queryResults), directExecutor());
    bindAsyncResponse(asyncResponse, response, responseExecutor);
}
Also used : AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) AsyncResponseHandler.bindAsyncResponse(io.airlift.jaxrs.AsyncResponseHandler.bindAsyncResponse) DataSize(io.airlift.units.DataSize) Duration(io.airlift.units.Duration) QueryResults(io.prestosql.client.QueryResults)

Example 5 with QueryResults

use of io.prestosql.client.QueryResults in project hetu-core by openlookeng.

the class TestProgressMonitor method newQueryResults.

private String newQueryResults(Integer partialCancelId, Integer nextUriId, List<Column> responseColumns, List<List<Object>> data, String state) {
    String queryId = "20160128_214710_00012_rk68b";
    QueryResults queryResults = new QueryResults(queryId, server.url("/query.html?" + queryId).uri(), partialCancelId == null ? null : server.url(format("/v1/stage/%s.%s", queryId, partialCancelId)).uri(), nextUriId == null ? null : server.url(format("/v1/statement/%s/%s", queryId, nextUriId)).uri(), responseColumns, data, new StatementStats(state, state.equals("QUEUED"), true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null, null), null, ImmutableList.of(), null, null);
    return QUERY_RESULTS_CODEC.toJson(queryResults);
}
Also used : StatementStats(io.prestosql.client.StatementStats) QueryResults(io.prestosql.client.QueryResults)

Aggregations

QueryResults (io.prestosql.client.QueryResults)10 Request (io.airlift.http.client.Request)6 List (java.util.List)4 Test (org.testng.annotations.Test)4 ImmutableList (com.google.common.collect.ImmutableList)3 URI (java.net.URI)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 HttpClient (io.airlift.http.client.HttpClient)1 HttpUriBuilder.uriBuilderFrom (io.airlift.http.client.HttpUriBuilder.uriBuilderFrom)1 JsonResponseHandler.createJsonResponseHandler (io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler)1 Builder.prepareGet (io.airlift.http.client.Request.Builder.prepareGet)1 Builder.preparePost (io.airlift.http.client.Request.Builder.preparePost)1 StaticBodyGenerator.createStaticBodyGenerator (io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator)1 UnexpectedResponseException (io.airlift.http.client.UnexpectedResponseException)1 JettyHttpClient (io.airlift.http.client.jetty.JettyHttpClient)1 AsyncResponseHandler.bindAsyncResponse (io.airlift.jaxrs.AsyncResponseHandler.bindAsyncResponse)1 JsonCodec (io.airlift.json.JsonCodec)1 JsonCodec.jsonCodec (io.airlift.json.JsonCodec.jsonCodec)1 JsonCodec.listJsonCodec (io.airlift.json.JsonCodec.listJsonCodec)1 Closeables.closeQuietly (io.airlift.testing.Closeables.closeQuietly)1