|
| 1 | +/* |
| 2 | + * Copyright (c) 2024, Salesforce, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.salesforce.datacloud.jdbc.examples; |
| 17 | + |
| 18 | +import static java.lang.Math.min; |
| 19 | + |
| 20 | +import com.salesforce.datacloud.jdbc.core.DataCloudConnection; |
| 21 | +import com.salesforce.datacloud.jdbc.core.DataCloudQueryStatus; |
| 22 | +import com.salesforce.datacloud.jdbc.core.DataCloudResultSet; |
| 23 | +import com.salesforce.datacloud.jdbc.core.partial.RowBased; |
| 24 | +import com.salesforce.datacloud.jdbc.hyper.HyperTestBase; |
| 25 | +import io.grpc.ManagedChannelBuilder; |
| 26 | +import java.sql.ResultSet; |
| 27 | +import java.sql.SQLException; |
| 28 | +import java.sql.Statement; |
| 29 | +import java.util.*; |
| 30 | +import lombok.extern.slf4j.Slf4j; |
| 31 | +import org.junit.jupiter.api.Test; |
| 32 | + |
| 33 | +/** |
| 34 | + * This example uses a locally spawned Hyper instance to demonstrate best practices around connecting to Hyper. |
| 35 | + * This consciously only uses the JDBC API in the core and no helpers (outside of this class) to provide self contained |
| 36 | + * examples. |
| 37 | + */ |
| 38 | +@Slf4j |
| 39 | +public class SubmitQueryAndConsumeResultsTest extends HyperTestBase { |
| 40 | + /** |
| 41 | + * This example shows how to create a Data Cloud Connection while still having full control over concerns like |
| 42 | + * authorization and tracing. |
| 43 | + */ |
| 44 | + @Test |
| 45 | + public void testBareBonesExecuteQuery() throws SQLException { |
| 46 | + // The connection properties |
| 47 | + Properties properties = new Properties(); |
| 48 | + |
| 49 | + // You can bring your own gRPC channels, setup in the way you like (mTLS / Plaintext / ...) and your own |
| 50 | + // interceptors as well as executors. |
| 51 | + ManagedChannelBuilder<?> channel = ManagedChannelBuilder.forAddress("127.0.0.1", instance.getPort()) |
| 52 | + .usePlaintext(); |
| 53 | + |
| 54 | + // Use the JDBC Driver interface |
| 55 | + try (DataCloudConnection conn = DataCloudConnection.fromChannel(channel, properties)) { |
| 56 | + try (Statement stmt = conn.createStatement()) { |
| 57 | + ResultSet rs = stmt.executeQuery("SELECT s FROM generate_series(1,10) s"); |
| 58 | + while (rs.next()) { |
| 59 | + System.out.println("Retrieved value:" + rs.getLong(1)); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Analyze the query status, as we have a query status we know that the query was last observed in a non failing |
| 67 | + * state. |
| 68 | + * |
| 69 | + * Offset must always be larger or equal to get row count (which would happen for typical next based pagination) |
| 70 | + */ |
| 71 | + private static long rowBasedStatusObjectRowsCheck(DataCloudQueryStatus queryStatus, long offset, long pageLimit) { |
| 72 | + // Check if we can at least return some data |
| 73 | + if (queryStatus.getRowCount() > offset) { |
| 74 | + return min(queryStatus.getRowCount() - offset, pageLimit); |
| 75 | + } |
| 76 | + // A negative count signals that no data is available |
| 77 | + return -1; |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Checks if the query status signals that all results are produced |
| 82 | + */ |
| 83 | + private static boolean allResultsProduced(DataCloudQueryStatus queryStatus) { |
| 84 | + return queryStatus.isResultProduced() || queryStatus.isExecutionFinished(); |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * This example shows how to use the row based pagination mode to get results segmented by approximate row count. |
| 89 | + * For the example we access the results in 2 row ranges and have an implementation where the application doesn't |
| 90 | + * know how many results would be produced in the end |
| 91 | + */ |
| 92 | + @Test |
| 93 | + public void testRowBasedPagination() throws SQLException { |
| 94 | + final int pageRowLimit = 2; |
| 95 | + long offset = 0; |
| 96 | + long page = 0; |
| 97 | + |
| 98 | + // The connection properties |
| 99 | + Properties properties = new Properties(); |
| 100 | + |
| 101 | + // You can bring your own gRPC channels, setup in the way you like (mTLS / Plaintext / ...) and your own |
| 102 | + // interceptors as well as executors. |
| 103 | + ManagedChannelBuilder<?> channel = ManagedChannelBuilder.forAddress("127.0.0.1", instance.getPort()) |
| 104 | + .usePlaintext(); |
| 105 | + |
| 106 | + try (DataCloudConnection conn = DataCloudConnection.fromChannel(channel, properties)) { |
| 107 | + // Submit the query and consume the initial page |
| 108 | + String queryId; |
| 109 | + try (Statement stmt = conn.createStatement()) { |
| 110 | + log.warn("Executing query using a single `ExecuteQuery` RPC Call"); |
| 111 | + ResultSet rs = stmt.executeQuery("SELECT s FROM generate_series(1,11) s"); |
| 112 | + queryId = ((DataCloudResultSet) rs).getQueryId(); |
| 113 | + // For this result set we as a consumer must currently implement the pagination limit ourselves |
| 114 | + int i = 0; |
| 115 | + while (rs.next() && (i++ < pageRowLimit)) { |
| 116 | + ++offset; |
| 117 | + System.out.println("Retrieved value: " + rs.getLong(1) + " on page " + page); |
| 118 | + } |
| 119 | + ++page; |
| 120 | + } |
| 121 | + |
| 122 | + // Consume further pages until the full result is consumed (could also be done on a new connection if |
| 123 | + // needed) |
| 124 | + // NIT: We should provide an API on the original result set to access the `DataCloudQueryStatus` that way, |
| 125 | + // if the query is already finished we don't need to do another network round-trip. |
| 126 | + Optional<DataCloudQueryStatus> cachedStatus = Optional.empty(); |
| 127 | + while (true) { |
| 128 | + // Try to make sure we have a status object |
| 129 | + if (!cachedStatus.isPresent()) { |
| 130 | + // Identify if there is more data? |
| 131 | + long lambdaOffset = offset; |
| 132 | + // In case of query error this could throw an runtime exception |
| 133 | + // NIT: What is the timeout enforced here? |
| 134 | + log.warn("Fetching query status using a single `GetQueryInfo` RPC call"); |
| 135 | + // NIT: Semantically I would want takeWhile here which is only available in Java 11 |
| 136 | + cachedStatus = conn.getQueryStatus(queryId) |
| 137 | + .filter(queryStatus -> |
| 138 | + (rowBasedStatusObjectRowsCheck(queryStatus, lambdaOffset, pageRowLimit) > 0) |
| 139 | + || allResultsProduced(queryStatus)) |
| 140 | + .findFirst(); |
| 141 | + |
| 142 | + // Query is still running |
| 143 | + // NIT: Check how we should handle this in the presence of timeouts |
| 144 | + if (!cachedStatus.isPresent()) { |
| 145 | + continue; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + long availableRows = rowBasedStatusObjectRowsCheck(cachedStatus.get(), offset, pageRowLimit); |
| 150 | + // Check if query completed and thus we can't produce more results |
| 151 | + if (availableRows <= 0) { |
| 152 | + if (allResultsProduced(cachedStatus.get())) { |
| 153 | + break; |
| 154 | + } else { |
| 155 | + // We need to fetch a new status in the next iteration |
| 156 | + // Due to the long-polling nature of `conn.getQueryStatus` this doesn't result in a busy |
| 157 | + // spinning loop even if the query is still executing |
| 158 | + cachedStatus = Optional.empty(); |
| 159 | + continue; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + // At this point we know that rows are available |
| 164 | + log.warn("Fetching query status using a single `GetQueryResult` RPC call"); |
| 165 | + try (ResultSet rs = |
| 166 | + conn.getRowBasedResultSet(queryId, offset, pageRowLimit, RowBased.Mode.SINGLE_RPC)) { |
| 167 | + while (rs.next()) { |
| 168 | + ++offset; |
| 169 | + System.out.println("Retrieved value: " + rs.getLong(1) + " on page " + page); |
| 170 | + } |
| 171 | + ++page; |
| 172 | + } |
| 173 | + } |
| 174 | + } |
| 175 | + log.warn("Completed"); |
| 176 | + } |
| 177 | +} |
0 commit comments