diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java index ce54b3dbeec4..adedbccc0519 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java @@ -69,7 +69,7 @@ public abstract class BigQueryBaseResultSet extends BigQueryNoOpsResultSet protected final Schema schema; protected final FieldList schemaFieldList; protected final boolean isNested; - protected boolean isClosed = false; + protected volatile boolean isClosed = false; protected boolean wasNull = false; // getMetaData() is commonly called inside row loops; cache the immutable wrapper and record // the adoption signal once per result set. ResultSet is single-threaded by JDBC contract. @@ -156,12 +156,8 @@ public String getQueryId() { @Override public void close() { - try { - if (statement != null && statement.isCloseOnCompletion() && !statement.hasMoreResults()) { - statement.close(); - } - } catch (SQLException ex) { - LOG.warning("Exception during ResultState.close() operation: %s", ex.getMessage()); + if (this.statement != null) { + this.statement.onResultSetClosed(this); } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java index 01cf735f88fd..9c1e38c7b086 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java @@ -406,6 +406,7 @@ private ArrayList deepCopyParameterList( @Override public int[] executeBatch() throws SQLException { validateExecution(); + prepareForExecution(); int[] result = new int[this.batchParameters.size()]; if (this.batchParameters.isEmpty()) { return result; @@ -424,6 +425,8 @@ public int[] executeBatch() throws SQLException { } if (useWriteAPI()) { + checkNotClosedOrCanceled(); + BigQueryConnection activeConn = requireOpenConnection(); long startTime = System.currentTimeMillis(); StatementExecution.Builder writeApiExecutionBuilder = StatementExecution.newBuilder() @@ -434,10 +437,10 @@ public int[] executeBatch() throws SQLException { .QUERY_API_TYPE_WRITE_API); try { int[] insertArray; - try (BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient()) { + try (BigQueryWriteClient writeClient = activeConn.getBigQueryWriteClient()) { LOG.info("Using Write API for bulk INSERT operation."); - long rowCount = bulkInsertWithWriteAPI(writeClient); + long rowCount = bulkInsertWithWriteAPI(writeClient, activeConn); insertArray = new int[Math.toIntExact(rowCount)]; Arrays.fill(insertArray, 1); } @@ -506,13 +509,14 @@ public int[] executeBatch() throws SQLException { } } - private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient) + private long bulkInsertWithWriteAPI( + BigQueryWriteClient bigQueryWriteClient, BigQueryConnection activeConn) throws DescriptorValidationException, IOException, InterruptedException, BigQueryJdbcException { LOG.finer("++enter++"); - RetrySettings retrySettings = this.connection.getRetrySettings(); + RetrySettings retrySettings = activeConn.getRetrySettings(); BigQueryJdbcBulkInsertWriter bulkInsertWriter = new BigQueryJdbcBulkInsertWriter(); bulkInsertWriter.initialize(this.insertTableName, bigQueryWriteClient, retrySettings); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java index 5e6041717c36..e60b38eb9aa2 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java @@ -72,6 +72,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; import java.lang.ref.ReferenceQueue; +import java.net.HttpURLConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -116,11 +117,11 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { // Reported when a failure carries no BigQuery or SQL error code, matching the fallback used by // TelemetryManager#extractErrorCode. private static final int UNKNOWN_ERROR_CODE = 1000; - protected ResultSet currentResultSet; - protected long currentUpdateCount = -1; + protected volatile ResultSet currentResultSet; + protected volatile long currentUpdateCount = -1; protected List jobIds = new ArrayList<>(); - protected JobIdWrapper parentJobId = null; - protected int currentJobIdIndex = -1; + protected volatile JobIdWrapper parentJobId = null; + protected volatile int currentJobIdIndex = -1; protected List batchQueries = new ArrayList<>(); protected volatile BigQueryConnection connection; private volatile Connection logicalConnection; @@ -129,10 +130,10 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { protected String connectionId; protected int maxFieldSize = 0; protected int maxRows = 0; - protected boolean isClosed = false; - protected boolean closeOnCompletion = false; + protected volatile boolean isClosed = false; + protected volatile boolean closeOnCompletion = false; protected Object cancelLock = new Object(); - protected boolean isCanceled = false; + protected volatile boolean isCanceled = false; protected boolean poolable; protected int queryTimeout = 0; protected SQLWarning warning; @@ -146,10 +147,6 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { final BigQuerySettings querySettings; - private BlockingQueue bigQueryFieldValueListWrapperBlockingQueue; - - private BlockingQueue arrowBatchWrapperBlockingQueue; - // Variables Required for the ReferenceQueue implementation static ReferenceQueue referenceQueueArrowRs = new ReferenceQueue<>(); static ReferenceQueue referenceQueueJsonRs = new ReferenceQueue<>(); @@ -218,7 +215,6 @@ public BigQueryStatement(BigQueryConnection connection) throws SQLException { } private void resetStatementFields() { - this.isCanceled = false; this.scriptQuery = null; this.parentJobId = null; this.currentJobIdIndex = -1; @@ -306,12 +302,14 @@ public ResultSet executeQuery(String sql) throws SQLException { } private ResultSet executeQueryImpl(String sql) throws SQLException { + prepareForExecution(); logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration); runQuery(sql, jobConfiguration.build()); + checkNotClosedOrCanceled(); if (!isSingularResultSet()) { throw new BigQueryJdbcException( "Query returned more than one or didn't return any ResultSet."); @@ -330,6 +328,7 @@ public long executeLargeUpdate(String sql) throws SQLException { } private long executeLargeUpdateImpl(String sql) throws SQLException { + prepareForExecution(); logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); @@ -364,6 +363,7 @@ public boolean execute(String sql) throws SQLException { } private boolean executeImpl(String sql) throws SQLException { + prepareForExecution(); logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); @@ -381,7 +381,8 @@ StatementType getStatementType(QueryJobConfiguration queryJobConfiguration) thro LOG.finer("++enter++"); // BQ Read-only tokens are not recommended to use, they have a lot of known flaws. // We're supporting them in a limited capacity, for pure SELECT statements. - if (this.connection != null && this.connection.isReadOnlyTokenUsed()) { + BigQueryConnection activeConn = requireOpenConnection(); + if (activeConn.isReadOnlyTokenUsed()) { LOG.warning( "Read-only token detected, skipping dry run and assuming StatementType is SELECT."); return StatementType.SELECT; @@ -392,7 +393,7 @@ StatementType getStatementType(QueryJobConfiguration queryJobConfiguration) thro try { job = bigQuery.create(JobInfo.of(dryRunJobConfiguration)); } catch (BigQueryException ex) { - if (ex.getMessage().contains("Syntax error")) { + if (isSyntaxError(ex)) { throw new BigQueryJdbcSqlSyntaxErrorException( "BigQueryException during getStatementType", ex); } @@ -426,7 +427,7 @@ QueryStatistics getQueryStatistics(QueryJobConfiguration queryJobConfiguration) job = this.bigQuery.create(JobInfo.of(dryRunJobConfiguration)); return job.getStatistics(); } catch (BigQueryException ex) { - if (ex.getMessage().contains("Syntax error")) { + if (isSyntaxError(ex)) { throw new BigQueryJdbcSqlSyntaxErrorException( "BigQueryException during getQueryStatistics", ex); } @@ -445,25 +446,27 @@ QueryStatistics getQueryStatistics(QueryJobConfiguration queryJobConfiguration) */ @Override public void close() throws SQLException { - if (isClosed()) { - return; + synchronized (cancelLock) { + if (this.isClosed) { + return; + } + this.isClosed = true; + this.isCanceled = true; } - this.isClosed = true; LOG.fine("Closing Statement %s.", this); - boolean cancelSucceeded = false; try { - cancelInternal(); // Cancels jobs and calls closeStatementResources(); no telemetry. - cancelSucceeded = true; + cancelRunningJobs(); } catch (SQLException e) { - LOG.warning("Failed to cancel statement during close().", e); + LOG.warning(e, "Failed to cancel statement during close()."); } finally { - if (!cancelSucceeded) { + try { closeStatementResources(); + } finally { + this.connection = null; + this.logicalConnection = null; + this.logicalStatementProxy = null; } - this.connection = null; - this.logicalConnection = null; - this.logicalStatementProxy = null; } } @@ -516,17 +519,23 @@ public void setQueryTimeout(int seconds) { @Override public void cancel() throws SQLException { LOG.finer("Statement %s cancelled", this); - cancelInternal(); + cancelRunningJobs(); + closeCurrentResultSet(/* honorCloseOnCompletion= */ false); + synchronized (cancelLock) { + this.currentUpdateCount = -1; + this.parentJobId = null; + this.currentJobIdIndex = -1; + } if (this.cancelRecorded.compareAndSet(false, true)) { recordFeature(DriverFeature.DRIVER_FEATURE_STATEMENT_CANCEL); } } /** - * Cancels running jobs and releases statement resources without recording telemetry. Used by - * {@link #close()}, where cancellation is housekeeping, not a user-initiated cancel. + * Cancels running jobs without recording telemetry or closing statement-level tracking. Shared by + * {@link #cancel()} and {@link #close()}. */ - private void cancelInternal() throws SQLException { + private void cancelRunningJobs() throws SQLException { LOG.finer("Statement %s cancelled internally", this); synchronized (cancelLock) { this.isCanceled = true; @@ -546,9 +555,6 @@ private void cancelInternal() throws SQLException { } jobIds.clear(); } - // If a ResultSet exists, then it will be closed as well, closing the - // ownedThreads - closeStatementResources(); } @Override @@ -588,33 +594,137 @@ public boolean getMoreResults() throws SQLException { private void closeStatementResources() throws SQLException { LOG.finer("++enter++"); - if (this.currentResultSet != null) { - // If Statement has 'CloseOnCompletion' set, resultset might - // call into the same function; In order to avoid stack overflow - // we will cleanup resultset before calling into 'close'. - ResultSet tmp = this.currentResultSet; - this.currentResultSet = null; - tmp.close(); - } + BigQueryConnection conn = this.connection; + closeCurrentResultSet(/* honorCloseOnCompletion= */ false); this.batchQueries.clear(); - this.arrowBatchWrapperBlockingQueue = null; - this.bigQueryFieldValueListWrapperBlockingQueue = null; - this.currentUpdateCount = -1; - this.currentJobIdIndex = -1; - if (this.connection != null) { - this.connection.removeStatement(this); + synchronized (cancelLock) { + this.currentUpdateCount = -1; + this.parentJobId = null; + this.currentJobIdIndex = -1; + } + if (conn != null) { + conn.removeStatement(this); + } + } + + void prepareForExecution() throws SQLException { + synchronized (cancelLock) { + checkClosed(); + this.isCanceled = false; + } + closeCurrentResultSet(/* honorCloseOnCompletion= */ false); + checkNotClosedOrCanceled(); + } + + private void closeCurrentResultSet(boolean honorCloseOnCompletion) throws SQLException { + ResultSet resultSetToClose; + synchronized (cancelLock) { + resultSetToClose = this.currentResultSet; + if (!honorCloseOnCompletion) { + // Clear currentResultSet before close() so onResultSetClosed does not trigger + // closeOnCompletion() when replacing, cancelling, or closing the Statement itself. + this.currentResultSet = null; + } + } + if (resultSetToClose == null) { + return; + } + if (!honorCloseOnCompletion) { + resultSetToClose.close(); + return; + } + // Keep currentResultSet assigned during close() so onResultSetClosed honors + // closeOnCompletion() when advancing past the final ResultSet via getMoreResults(). + try { + resultSetToClose.close(); + } finally { + synchronized (cancelLock) { + if (this.currentResultSet == resultSetToClose) { + this.currentResultSet = null; + } + } + } + } + + void onResultSetClosed(ResultSet closedResultSet) { + if (this.connectionId != null) { + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { + onResultSetClosedInternal(closedResultSet); + } + return; + } + onResultSetClosedInternal(closedResultSet); + } + + private void onResultSetClosedInternal(ResultSet closedResultSet) { + boolean willCloseStatement = + closedResultSet == this.currentResultSet + && !this.isClosed + && isCloseOnCompletion() + && !hasMoreResults(); + if (willCloseStatement) { + try { + close(); + } catch (SQLException ex) { + LOG.warning(ex, "Exception during ResultSet.close() operation."); + } } } + private static boolean isSyntaxError(BigQueryException ex) { + return ex.getMessage() != null && ex.getMessage().contains("Syntax error"); + } + + private static boolean isTerminalJobError(BigQueryException ex) { + int code = ex.getCode(); + return code == HttpURLConnection.HTTP_BAD_REQUEST || (code == 0 && ex.getError() != null); + } + private boolean isSingularResultSet() { - return this.currentResultSet != null - && (this.parentJobId == null || this.parentJobId.getJobs().size() == 1); + JobIdWrapper parent = this.parentJobId; + return this.currentResultSet != null && (parent == null || parent.getJobs().size() == 1); } private String generateJobId() { return JDBC_JOB_PREFIX + UUID.randomUUID().toString(); } + private void cancelJobBestEffort(Job job) { + try { + job.cancel(); + } catch (RuntimeException cancelEx) { + LOG.fine("Best-effort job cancellation failed: %s", cancelEx.getMessage()); + } + } + + private void cancelJobIdBestEffort(JobId jobId) { + if (this.bigQuery == null || jobId.getJob() == null) { + return; + } + try { + this.bigQuery.cancel(jobId); + } catch (RuntimeException cancelEx) { + LOG.fine("Best-effort job cancellation failed for %s: %s", jobId, cancelEx.getMessage()); + } + } + + void checkNotClosedOrCanceled() throws BigQueryJdbcException { + if (this.isClosed) { + throw new BigQueryJdbcException("Statement was closed."); + } + if (this.isCanceled) { + throw new BigQueryJdbcException("Query was cancelled."); + } + } + + BigQueryConnection requireOpenConnection() throws BigQueryJdbcException { + BigQueryConnection activeConn = this.connection; + if (activeConn == null || this.isClosed) { + throw new BigQueryJdbcException("Statement was closed."); + } + return activeConn; + } + private class ExecuteResult { public final TableResult tableResult; public final Job job; @@ -628,20 +738,36 @@ private class ExecuteResult { @InternalApi ExecuteResult executeJob(QueryJobConfiguration jobConfiguration) throws InterruptedException, BigQueryException, BigQueryJdbcException { + return executeJob(jobConfiguration, this.connection); + } + + private ExecuteResult executeJob(QueryJobConfiguration jobConfiguration, BigQueryConnection conn) + throws InterruptedException, BigQueryException, BigQueryJdbcException { LOG.finer("++enter++"); Job job = null; + if (conn == null) { + throw new BigQueryJdbcException("Statement was closed."); + } // Location is not properly passed from the connection, so we need to explicitly set it. // Only populate a client JobId when destinationTable != null (which already disables jobless // fast query), making jobs.insert retries idempotent for WRITE_EMPTY temp tables. - JobId.Builder jobIdBuilder = JobId.newBuilder().setLocation(connection.getLocation()); + JobId.Builder jobIdBuilder = JobId.newBuilder().setLocation(conn.getLocation()); if (jobConfiguration.getDestinationTable() != null) { jobIdBuilder.setJob(generateJobId()); } JobId jobId = jobIdBuilder.build(); - Object result = bigQuery.queryWithTimeout(jobConfiguration, jobId, null); + Object result; + try { + result = bigQuery.queryWithTimeout(jobConfiguration, jobId, null); + } catch (InterruptedException | RuntimeException ex) { + if (!(ex instanceof BigQueryException && isTerminalJobError((BigQueryException) ex))) { + cancelJobIdBestEffort(jobId); + } + throw ex; + } if (result instanceof TableResult) { TableResult tableResult = (TableResult) result; - saveSessionIdIfPresent(tableResult); + saveSessionIdIfPresent(tableResult, conn); this.currentExecutionBuilder.setQueryApiType(QueryApiType.QUERY_API_TYPE_JOBLESS_QUERY); return new ExecuteResult(tableResult, null); } @@ -652,21 +778,37 @@ ExecuteResult executeJob(QueryJobConfiguration jobConfiguration) throw new BigQueryJdbcException("Unexpected result type from queryWithTimeout"); } + boolean abortedBeforeRegister; synchronized (cancelLock) { - if (isCanceled) { - job.cancel(); - throw new BigQueryJdbcException("Query was cancelled."); + abortedBeforeRegister = this.isClosed || this.isCanceled; + if (!abortedBeforeRegister) { + jobId = job.getJobId(); + jobIds.add(jobId); + } + } + if (abortedBeforeRegister) { + cancelJobBestEffort(job); + checkNotClosedOrCanceled(); + } + LOG.info("Query submitted with Job ID: %s", jobId != null ? jobId.getJob() : null); + TableResult tableResult; + try { + tableResult = + job.getQueryResults(QueryResultsOption.pageSize(querySettings.getMaxResultPerPage())); + } catch (InterruptedException | RuntimeException ex) { + if (!(ex instanceof BigQueryException && isTerminalJobError((BigQueryException) ex))) { + cancelJobBestEffort(job); + } + throw ex; + } finally { + synchronized (cancelLock) { + jobIds.remove(jobId); } - jobId = job.getJobId(); - jobIds.add(jobId); } - LOG.info("Query submitted with Job ID: " + job.getJobId().getJob()); - TableResult tableResult = - job.getQueryResults(QueryResultsOption.pageSize(querySettings.getMaxResultPerPage())); synchronized (cancelLock) { - jobIds.remove(jobId); + checkNotClosedOrCanceled(); } - saveSessionIdIfPresent(tableResult); + saveSessionIdIfPresent(tableResult, conn); if (jobId != null && bigQuery != null) { Job refreshedJob = bigQuery.getJob(jobId); if (refreshedJob != null) { @@ -677,14 +819,14 @@ ExecuteResult executeJob(QueryJobConfiguration jobConfiguration) return new ExecuteResult(tableResult, job); } - private void saveSessionIdIfPresent(TableResult tableResult) { - if (this.connection == null || tableResult == null) { + private void saveSessionIdIfPresent(TableResult tableResult, BigQueryConnection conn) { + if (conn == null || tableResult == null) { return; } if (tableResult.getSessionInfo() != null) { String sessionId = tableResult.getSessionInfo().getSessionId(); if (sessionId != null && !sessionId.isEmpty()) { - this.connection.initSessionInfo(sessionId); + conn.initSessionInfo(sessionId); } } } @@ -724,21 +866,42 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx jobConfiguration.toBuilder().setJobTimeoutMs(Long.valueOf(queryTimeout) * 1000).build(); } + boolean executionStarted = false; + BigQueryConnection conn = null; + long startTime = System.currentTimeMillis(); // Overwritten by the catch blocks below. The initial value covers failures that reach none of // them, such as an uncaught RuntimeException, so a failure is never reported without a code. int errorCode = UNKNOWN_ERROR_CODE; try { - resetStatementFields(); - ExecuteResult executeResult = executeJob(jobConfiguration); + synchronized (cancelLock) { + checkClosed(); + if (this.isCanceled) { + throw new BigQueryJdbcException("Query was cancelled."); + } + executionStarted = true; + conn = this.connection; + resetStatementFields(); + } + ExecuteResult executeResult = executeJob(jobConfiguration, conn); + checkNotClosedOrCanceled(); StatementType statementType = getStatementType(executeResult); this.currentExecutionBuilder.setStatementType( TelemetryManager.toStatementType(statementType)); SqlType queryType = getQueryType(jobConfiguration, statementType); + checkNotClosedOrCanceled(); handleQueryResult(query, executeResult.tableResult, queryType, executeResult.job); + boolean aborted; + synchronized (cancelLock) { + aborted = this.isClosed || this.isCanceled; + } + if (aborted) { + closeCurrentResultSet(/* honorCloseOnCompletion= */ false); + checkNotClosedOrCanceled(); + } this.currentExecutionBuilder.setStatus( com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_SUCCESS); @@ -749,7 +912,7 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx throw new BigQueryJdbcException("Interrupted during runQuery", ex); } catch (BigQueryException ex) { errorCode = TelemetryManager.extractErrorCode(ex); - if (ex.getMessage().contains("Syntax error")) { + if (isSyntaxError(ex)) { throw new BigQueryJdbcSqlSyntaxErrorException("BigQueryException during runQuery", ex); } throw new BigQueryJdbcException("BigQueryException during runQuery", ex); @@ -759,19 +922,22 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx } finally { long durationMs = System.currentTimeMillis() - startTime; - // Any path that did not reach STATUS_SUCCESS is a failure, whether it was caught above or - // propagated as an uncaught RuntimeException, so failures are never reported as UNSPECIFIED. - if (this.currentExecutionBuilder.getStatus() - == com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_UNSPECIFIED) { - this.currentExecutionBuilder - .setStatus( - isCanceled - ? com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_CANCELLED - : com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR) - .setErrorCode(errorCode); - } + if (executionStarted) { + // Any path that did not reach STATUS_SUCCESS is a failure, whether it was caught above or + // propagated as an uncaught RuntimeException, so failures are never reported as + // UNSPECIFIED. + if (this.currentExecutionBuilder.getStatus() + == com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_UNSPECIFIED) { + this.currentExecutionBuilder + .setStatus( + isCanceled + ? com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_CANCELLED + : com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR) + .setErrorCode(errorCode); + } - recordExecution(this.currentExecutionBuilder, durationMs); + recordExecution(this.currentExecutionBuilder, durationMs); + } } } @@ -831,13 +997,25 @@ QueryJobConfiguration.Builder setDestinationDatasetAndTableInJobConfig( } Job getNextJob() { - if (this.parentJobId == null) { + JobIdWrapper parent = this.parentJobId; + if (parent == null) { return null; } - while (this.currentJobIdIndex + 1 < this.parentJobId.getJobs().size()) { - this.currentJobIdIndex += 1; - Job currentJob = this.parentJobId.getJobs().get(this.currentJobIdIndex); + List jobs = parent.getJobs(); + while (true) { + int nextIndex; + synchronized (cancelLock) { + if (this.isClosed || this.isCanceled) { + return null; + } + nextIndex = this.currentJobIdIndex + 1; + if (nextIndex < 0 || nextIndex >= jobs.size()) { + return null; + } + this.currentJobIdIndex = nextIndex; + } + Job currentJob = jobs.get(nextIndex); QueryStatistics queryStatistics = currentJob.getStatistics(); ScriptStatistics scriptStatistics = queryStatistics.getScriptStatistics(); // EXPRESSION jobs are not relevant for customer query and can be @@ -847,7 +1025,6 @@ Job getNextJob() { return currentJob; } } - return null; } SqlType handleQueryResult(String query, Job job) throws SQLException, InterruptedException { @@ -969,15 +1146,17 @@ private void updateAffectedRowCount(Long count) throws SQLException { } @InternalApi - BigQueryReadClient getBigQueryReadClient() { + BigQueryReadClient getBigQueryReadClient() throws BigQueryJdbcException { + BigQueryConnection activeConn = requireOpenConnection(); if (this.bigQueryReadClient == null) { - this.bigQueryReadClient = this.connection.getBigQueryReadClient(); + this.bigQueryReadClient = activeConn.getBigQueryReadClient(); } return this.bigQueryReadClient; } @InternalApi - ReadSession getReadSession(CreateReadSessionRequest readSessionRequest) { + ReadSession getReadSession(CreateReadSessionRequest readSessionRequest) + throws BigQueryJdbcException { LOG.finer("++enter++"); return getBigQueryReadClient().createReadSession(readSessionRequest); } @@ -1022,11 +1201,11 @@ ResultSet processArrowResultSet(TableResult results, Job job) throws SQLExceptio .setMaxStreamCount(1); ReadSession readSession = getReadSession(builder.build()); - this.arrowBatchWrapperBlockingQueue = new LinkedBlockingDeque<>(getArrowBufferSize()); + BlockingQueue arrowBatchQueue = + new LinkedBlockingDeque<>(getArrowBufferSize()); // deserialize and populate the buffer async, so that the client isn't blocked populateBufferWorker = - populateArrowBufferedQueue( - readSession, this.arrowBatchWrapperBlockingQueue, getBigQueryReadClient()); + populateArrowBufferedQueue(readSession, arrowBatchQueue, getBigQueryReadClient()); BigQueryArrowResultSet arrowResultSet = BigQueryArrowResultSet.of( @@ -1034,7 +1213,7 @@ ResultSet processArrowResultSet(TableResult results, Job job) throws SQLExceptio getArrowSchema(readSession), totalRows, this, - this.arrowBatchWrapperBlockingQueue, + arrowBatchQueue, populateBufferWorker, this.bigQuery, job); @@ -1052,13 +1231,30 @@ ResultSet processArrowResultSet(TableResult results, Job job) throws SQLExceptio if (populateBufferWorker != null) { populateBufferWorker.cancel(true); } - if (ex instanceof OutOfMemoryError || ex instanceof RejectedExecutionException) { + if (ex instanceof OutOfMemoryError) { + throw new BigQueryJdbcException( + "Failed to execute query: Unable to allocate background threads to process the query" + + " results. Connection-scoped thread pool limit of 100 threads was reached or" + + " system is out of memory.", + ex); + } + if (this.isClosed) { + if (ex instanceof BigQueryJdbcException + && "Statement was closed.".equals(ex.getMessage())) { + throw (BigQueryJdbcException) ex; + } + throw new BigQueryJdbcException("Statement was closed.", ex); + } + if (ex instanceof RejectedExecutionException) { throw new BigQueryJdbcException( "Failed to execute query: Unable to allocate background threads to process the query" + " results. Connection-scoped thread pool limit of 100 threads was reached or" + " system is out of memory.", ex); } + if (ex instanceof BigQueryJdbcException) { + throw (BigQueryJdbcException) ex; + } throw new BigQueryJdbcException(ex.getMessage(), ex); } } @@ -1081,10 +1277,11 @@ private TableReadOptions buildTableReadOptions() { Future populateArrowBufferedQueue( ReadSession readSession, BlockingQueue arrowBatchWrapperBlockingQueue, - BigQueryReadClient bqReadClient) { + BigQueryReadClient bqReadClient) + throws BigQueryJdbcException { LOG.finer("++enter++"); - ExecutorService executor = connection.getExecutorService(); + ExecutorService executor = requireOpenConnection().getExecutorService(); Runnable arrowStreamProcessor = Context.current() @@ -1302,7 +1499,8 @@ BigQueryJsonResultSet processJsonResultSet(TableResult results, Job job) throws Schema schema = results.getSchema(); long totalRows = getEffectiveTotalRows(results); - this.bigQueryFieldValueListWrapperBlockingQueue = new LinkedBlockingDeque<>(getBufferSize()); + BlockingQueue fieldValueListQueue = + new LinkedBlockingDeque<>(getBufferSize()); BlockingQueue> rpcResponseQueue = new LinkedBlockingDeque<>(getPageCacheSize(getBufferSize(), schema)); @@ -1312,11 +1510,7 @@ BigQueryJsonResultSet processJsonResultSet(TableResult results, Job job) throws // Task to make rpc calls to fetch data from the server Future nextPageWorker = runNextPageTaskAsync( - results, - results.getNextPageToken(), - jobId, - rpcResponseQueue, - this.bigQueryFieldValueListWrapperBlockingQueue); + results, results.getNextPageToken(), jobId, rpcResponseQueue, fieldValueListQueue); taskList.add(nextPageWorker); } else { try { @@ -1333,8 +1527,7 @@ BigQueryJsonResultSet processJsonResultSet(TableResult results, Job job) throws // Task to parse data received from the server to client library objects Future populateBufferWorker = - parseAndPopulateRpcDataAsync( - schema, this.bigQueryFieldValueListWrapperBlockingQueue, rpcResponseQueue); + parseAndPopulateRpcDataAsync(schema, fieldValueListQueue, rpcResponseQueue); taskList.add(populateBufferWorker); } catch (Exception | OutOfMemoryError e) { for (Future task : taskList) { @@ -1342,7 +1535,20 @@ BigQueryJsonResultSet processJsonResultSet(TableResult results, Job job) throws task.cancel(true); } } - if (e instanceof RejectedExecutionException || e instanceof OutOfMemoryError) { + if (e instanceof OutOfMemoryError) { + throw new BigQueryJdbcException( + "Failed to execute query: Unable to allocate background threads to process the query" + + " results. Connection-scoped thread pool limit of 100 threads was reached or" + + " system is out of memory.", + e); + } + if (this.isClosed) { + if (e instanceof BigQueryJdbcException && "Statement was closed.".equals(e.getMessage())) { + throw (BigQueryJdbcException) e; + } + throw new BigQueryJdbcException("Statement was closed.", e); + } + if (e instanceof RejectedExecutionException) { throw new BigQueryJdbcException( "Failed to execute query: Unable to allocate background threads to process the query" + " results. Connection-scoped thread pool limit of 100 threads was reached or" @@ -1361,13 +1567,7 @@ BigQueryJsonResultSet processJsonResultSet(TableResult results, Job job) throws BigQueryJsonResultSet jsonResultSet = BigQueryJsonResultSet.of( - schema, - totalRows, - this.bigQueryFieldValueListWrapperBlockingQueue, - this, - jsonWorkers, - this.bigQuery, - job); + schema, totalRows, fieldValueListQueue, this, jsonWorkers, this.bigQuery, job); jsonResultSet.setJobId(jobId); jsonResultSet.setQueryId(results.getQueryId()); if (job == null && jobId == null) { @@ -1409,14 +1609,16 @@ Future runNextPageTaskAsync( String firstPageToken, JobId jobId, BlockingQueue> rpcResponseQueue, - BlockingQueue bigQueryFieldValueListWrapperBlockingQueue) { + BlockingQueue bigQueryFieldValueListWrapperBlockingQueue) + throws BigQueryJdbcException { LOG.finest("++enter++"); // parse and put the first page in the pageCache before the other pages are parsed from the RPC // calls populateFirstPage(result, rpcResponseQueue); SpanContext parentSpanContext = Span.current().getSpanContext(); - ExecutorService executor = connection.getExecutorService(); + BigQueryConnection activeConn = requireOpenConnection(); + ExecutorService executor = activeConn.getExecutorService(); // This thread makes the RPC calls and paginates Runnable nextPageTask = @@ -1439,7 +1641,7 @@ Future runNextPageTaskAsync( } SpanBuilder spanBuilder = - connection.getTracer().spanBuilder("BigQueryStatement.pagination"); + activeConn.getTracer().spanBuilder("BigQueryStatement.pagination"); if (parentSpanContext.isValid()) { spanBuilder.addLink(parentSpanContext); } @@ -1502,10 +1704,11 @@ Future runNextPageTaskAsync( Future parseAndPopulateRpcDataAsync( Schema schema, BlockingQueue bigQueryFieldValueListWrapperBlockingQueue, - BlockingQueue> rpcResponseQueue) { + BlockingQueue> rpcResponseQueue) + throws BigQueryJdbcException { LOG.finer("++enter++"); - ExecutorService executor = connection.getExecutorService(); + ExecutorService executor = requireOpenConnection().getExecutorService(); Runnable populateBufferRunnable = Context.current() @@ -1653,7 +1856,7 @@ TableId getDestinationTable(JobId jobId) { return ((QueryJobConfiguration) job.getConfiguration()).getDestinationTable(); } - QueryJobConfiguration.Builder getJobConfig(String query) { + QueryJobConfiguration.Builder getJobConfig(String query) throws BigQueryJdbcException { LOG.finer("++enter++"); QueryJobConfiguration.Builder queryConfigBuilder = QueryJobConfiguration.newBuilder(query); if (this.querySettings.getJobTimeoutMs() > 0) { @@ -1676,11 +1879,10 @@ QueryJobConfiguration.Builder getJobConfig(String query) { queryConfigBuilder.setUseQueryCache(this.querySettings.getUseQueryCache()); queryConfigBuilder.setMaxResults(this.querySettings.getMaxResultPerPage()); - // Only reachable from execute paths, which call checkClosed() first, so this.connection is - // non-null here; close() is the only thing that nulls it. - BigQueryConnection.SessionState snapshot = this.connection.getSessionStateSnapshot(); + BigQueryConnection activeConn = requireOpenConnection(); + BigQueryConnection.SessionState snapshot = activeConn.getSessionStateSnapshot(); ConnectionProperty sessionProperty = snapshot.sessionInfo; - boolean isSessionEnabled = this.connection.isSessionEnabled(); + boolean isSessionEnabled = activeConn.isSessionEnabled(); List queryProperties = snapshot.queryProperties; List props = @@ -1695,7 +1897,7 @@ QueryJobConfiguration.Builder getJobConfig(String query) { } } else if (isSessionEnabled) { queryConfigBuilder.setCreateSession(true); - this.connection.markSessionCreatedByDriver(); + activeConn.markSessionCreatedByDriver(); } if (!props.isEmpty()) { @@ -1887,6 +2089,7 @@ public int[] executeBatch() throws SQLException { } private int[] executeBatchImpl(String combinedQueries) throws SQLException { + prepareForExecution(); int[] result = new int[this.batchQueries.size()]; if (this.batchQueries.isEmpty()) { return result; @@ -1926,10 +2129,11 @@ public Connection getConnection() { } public boolean hasMoreResults() { - if (this.parentJobId == null) { + JobIdWrapper parent = this.parentJobId; + if (parent == null) { return false; } - return this.currentJobIdIndex + 1 < this.parentJobId.getJobs().size(); + return this.currentJobIdIndex + 1 < parent.getJobs().size(); } @Override @@ -1945,13 +2149,10 @@ private boolean getMoreResultsImpl(int current) throws SQLException { } try { - if (this.currentResultSet != null) { - this.currentResultSet.close(); - this.currentResultSet = null; - // Statement can be closed if it was the last result - if (isClosed) { - return false; - } + closeCurrentResultSet(/* honorCloseOnCompletion= */ true); + // Statement can be closed if it was the last result + if (isClosed) { + return false; } Job currentJob = getNextJob(); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java index 244852e166e5..48a2c4727a67 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java @@ -30,6 +30,7 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -71,6 +72,7 @@ import com.google.cloud.bigquery.TableId; import com.google.cloud.bigquery.TableResult; import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.exception.BigQueryJdbcSqlSyntaxErrorException; import com.google.cloud.bigquery.jdbc.BigQueryStatement.JobIdWrapper; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; @@ -532,7 +534,7 @@ public void testSetExtraLabels() { } @Test - public void testGetJobConfigWithExtraLabels() { + public void testGetJobConfigWithExtraLabels() throws SQLException { Map extraLabels = new HashMap<>(); extraLabels.put("extraKey1", "extraVal1"); extraLabels.put("key1", "overrideVal1"); // Override connection label @@ -822,9 +824,13 @@ public void testCancelDoesNotRollbackTransaction() throws SQLException { statementSpy.cancel(); - // Cancel should call bigquery.cancel() but not rollback the transaction + // Cancel should call bigquery.cancel(), keep the open statement tracked, and not rollback verify(bigquery).cancel(eq(jobId)); verify(bigQueryConnection, Mockito.never()).rollback(); + verify(bigQueryConnection, Mockito.never()).removeStatement(statementSpy); + + statementSpy.close(); + verify(bigQueryConnection, Mockito.never()).rollback(); verify(bigQueryConnection).removeStatement(statementSpy); } @@ -2212,4 +2218,409 @@ public void testLargeResultTable_withoutLargeResultDatasetUnderStandardSqlThrows verify(bigquery, never()).create(any(JobInfo.class)); verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); } + + @Test + public void testStatement_closeOnCompletionAndReexecution() throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + BigQueryStatement statement = new BigQueryStatement(bigQueryConnection); + statement.closeOnCompletion(); + + ResultSet rs1 = statement.executeQuery("SELECT 1"); + ResultSet rs2 = statement.executeQuery("SELECT 2"); + assertFalse(statement.isClosed()); + assertTrue(rs1.isClosed()); + assertFalse(rs2.isClosed()); + + rs2.close(); + assertTrue(statement.isClosed()); + } + + @Test + public void testPreparedStatement_executeBatchClosesOpenResultSet() throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + try (BigQueryPreparedStatement ps = + new BigQueryPreparedStatement(bigQueryConnection, "SELECT 1", true)) { + ResultSet psRs = ps.executeQuery(); + assertFalse(psRs.isClosed()); + assertEquals(0, ps.executeBatch().length); + assertTrue(psRs.isClosed()); + } + } + + @Test + public void testStatement_scriptCloseOnCompletionAdvancesUntilFinalResult() throws Exception { + Job childJob1 = + createScriptChildJobMock("script-child-1", StatementType.SELECT, 1L, 1L, false, null); + Job childJob2 = + createScriptChildJobMock("script-child-2", StatementType.SELECT, 1L, 1L, false, null); + @SuppressWarnings("unchecked") + Page childJobsPage = mock(Page.class); + doReturn(Arrays.asList(childJob2, childJob1)).when(childJobsPage).iterateAll(); + doReturn(childJobsPage).when(bigquery).listJobs(any(JobListOption.class)); + setupMockQueryResults(JobId.of("script-parent-job"), StatementType.SCRIPT, null); + + BigQueryStatement scriptStmt = new BigQueryStatement(bigQueryConnection); + scriptStmt.closeOnCompletion(); + assertTrue(scriptStmt.execute("SELECT 1; SELECT 2;")); + assertFalse(scriptStmt.isClosed()); + assertTrue(scriptStmt.getMoreResults()); + assertFalse(scriptStmt.isClosed()); + assertFalse(scriptStmt.getMoreResults()); + assertTrue(scriptStmt.isClosed()); + } + + @Test + public void testStatement_bestEffortJobCancelFailureDoesNotMaskQueryException() throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + Job failingCancelJob = setupMockLargeResultJobQuery(StatementType.SELECT, null); + doThrow(new BigQueryException(500, "Query failed")) + .when(failingCancelJob) + .getQueryResults(any(QueryResultsOption.class)); + doThrow(new BigQueryException(400, "Job is already in state DONE")) + .when(failingCancelJob) + .cancel(); + try (BigQueryStatement cancelFailStmt = new BigQueryStatement(bigQueryConnection)) { + BigQueryJdbcException ex = + assertThrows(BigQueryJdbcException.class, () -> cancelFailStmt.executeQuery("SELECT 9")); + assertTrue(ex.getCause().getMessage().contains("Query failed")); + } + } + + @Test + public void testStatement_concurrentCancelKeepsStatementOpenUntilConnectionClose() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .toString(); + Dataset datasetWithTtl = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(datasetWithTtl).getDefaultTableLifetime(); + doReturn(datasetWithTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + + Job jobMock = setupMockLargeResultJobQuery(StatementType.SELECT, null); + TableResult completedResult = mock(TableResult.class); + doReturn(Schema.of()).when(completedResult).getSchema(); + doReturn(StatementType.SELECT).when(completedResult).getStatementType(); + + CountDownLatch enteredGetQueryResults = new CountDownLatch(1); + CountDownLatch allowGetQueryResultsReturn = new CountDownLatch(1); + Mockito.when(jobMock.getQueryResults(any(QueryResultsOption.class))) + .thenAnswer( + invocation -> { + enteredGetQueryResults.countDown(); + assertTrue(allowGetQueryResultsReturn.await(5, TimeUnit.SECONDS)); + return completedResult; + }); + + ExecutorService callerPool = Executors.newSingleThreadExecutor(); + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url)) { + Statement stmt = conn.createStatement(); + BigQueryStatement unwrappedStmt = stmt.unwrap(BigQueryStatement.class); + + Future queryFuture = callerPool.submit(() -> stmt.executeQuery("SELECT 1")); + assertTrue(enteredGetQueryResults.await(5, TimeUnit.SECONDS)); + + stmt.cancel(); + verify(bigquery).cancel(any(JobId.class)); + assertTrue(conn.openStatements.contains(stmt)); + assertFalse(unwrappedStmt.isClosed()); + + allowGetQueryResultsReturn.countDown(); + ExecutionException execEx = + assertThrows(ExecutionException.class, () -> queryFuture.get(5, TimeUnit.SECONDS)); + assertThat(execEx.getCause()).isInstanceOf(BigQueryJdbcException.class); + assertNull(unwrappedStmt.getResultSet()); + + conn.close(); + assertTrue(unwrappedStmt.isClosed()); + } finally { + callerPool.shutdownNow(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testStatement_concurrentCloseOrCancelDuringHandleQueryResultCancelsWorker( + boolean closeStatement) throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + BigQueryStatement stmtSpy = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + Future workerFuture = mock(Future.class); + doReturn(workerFuture).when(stmtSpy).runNextPageTaskAsync(any(), any(), any(), any(), any()); + CountDownLatch enteredResultSetCreation = new CountDownLatch(1); + CountDownLatch abortFinished = new CountDownLatch(1); + Mockito.doAnswer( + invocation -> { + BigQueryJsonResultSet resultSet = (BigQueryJsonResultSet) invocation.callRealMethod(); + enteredResultSetCreation.countDown(); + assertTrue(abortFinished.await(5, TimeUnit.SECONDS)); + return resultSet; + }) + .when(stmtSpy) + .processJsonResultSet(any(TableResult.class), any()); + + ExecutorService callerPool = Executors.newSingleThreadExecutor(); + try { + Future queryFuture = callerPool.submit(() -> stmtSpy.executeQuery("SELECT 1")); + assertTrue(enteredResultSetCreation.await(5, TimeUnit.SECONDS)); + + if (closeStatement) { + stmtSpy.close(); + } else { + stmtSpy.cancel(); + } + abortFinished.countDown(); + + ExecutionException execEx = + assertThrows(ExecutionException.class, () -> queryFuture.get(5, TimeUnit.SECONDS)); + assertThat(execEx.getCause()).isInstanceOf(BigQueryJdbcException.class); + assertThat(execEx.getCause().getMessage()).contains(closeStatement ? "closed" : "cancelled"); + assertEquals(closeStatement, stmtSpy.isClosed()); + assertNull(stmtSpy.getResultSet()); + verify(workerFuture).cancel(true); + } finally { + callerPool.shutdownNow(); + } + } + + @Test + public void testStatement_concurrentCloseBeforeRunQueryAbortsWithoutSubmittingJob() + throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + Dataset datasetWithTtl = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(datasetWithTtl).getDefaultTableLifetime(); + + CountDownLatch enteredGetDataset = new CountDownLatch(1); + CountDownLatch closeFinished = new CountDownLatch(1); + Mockito.when(bigquery.getDataset(eq(DatasetId.of(SCRATCH_DATASET)))) + .thenAnswer( + invocation -> { + enteredGetDataset.countDown(); + assertTrue(closeFinished.await(5, TimeUnit.SECONDS)); + return datasetWithTtl; + }); + + BigQueryStatement statement = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + ExecutorService callerPool = Executors.newSingleThreadExecutor(); + try { + Future queryFuture = callerPool.submit(() -> statement.executeQuery("SELECT 1")); + assertTrue(enteredGetDataset.await(5, TimeUnit.SECONDS)); + + statement.close(); + closeFinished.countDown(); + + ExecutionException execEx = + assertThrows(ExecutionException.class, () -> queryFuture.get(5, TimeUnit.SECONDS)); + assertThat(execEx.getCause()).isInstanceOf(BigQueryJdbcException.class); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + verify(statement, never()).recordExecution(any(), anyLong()); + } finally { + callerPool.shutdownNow(); + } + } + + @Test + public void testStatement_concurrentCloseDuringGetJobThrowsClosedNoNpe() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .toString(); + Dataset datasetWithTtl = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(datasetWithTtl).getDefaultTableLifetime(); + doReturn(datasetWithTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + + StubbedLargeResultJob stubbedJob = createStubbedLargeResultJob(StatementType.SELECT, null); + Map jobsById = new ConcurrentHashMap<>(); + CountDownLatch enteredGetJob = new CountDownLatch(1); + CountDownLatch closeFinished = new CountDownLatch(1); + + Mockito.doAnswer( + invocation -> { + QueryJobConfiguration config = invocation.getArgument(0); + JobId submittedJobId = invocation.getArgument(1); + stubbedJob.bind(config, submittedJobId); + jobsById.put(submittedJobId, stubbedJob.job); + return stubbedJob.job; + }) + .when(bigquery) + .queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + Mockito.doAnswer( + invocation -> { + enteredGetJob.countDown(); + assertTrue(closeFinished.await(5, TimeUnit.SECONDS)); + return jobsById.get(invocation.getArgument(0)); + }) + .when(bigquery) + .getJob(any(JobId.class)); + + ExecutorService callerPool = Executors.newSingleThreadExecutor(); + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url)) { + Statement stmt = conn.createStatement(); + Future queryFuture = callerPool.submit(() -> stmt.executeQuery("SELECT 1")); + assertTrue(enteredGetJob.await(5, TimeUnit.SECONDS)); + + stmt.close(); + closeFinished.countDown(); + + ExecutionException execEx = + assertThrows(ExecutionException.class, () -> queryFuture.get(5, TimeUnit.SECONDS)); + assertThat(execEx.getCause()).isInstanceOf(BigQueryJdbcException.class); + assertEquals("Statement was closed.", execEx.getCause().getMessage()); + assertNull(execEx.getCause().getCause()); + assertTrue(stmt.isClosed()); + assertNull(stmt.getResultSet()); + } finally { + callerPool.shutdownNow(); + } + } + + @Test + public void testStatement_concurrentCloseInsideResultSetCreationThrowsClosedNoNpe() + throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + + // 1. JSON path: Statement.close() lands inside processJsonResultSet before + // requireOpenConnection() runs in runNextPageTaskAsync() -> clean "Statement was closed." + // with no NPE and no leaked background worker. + setupMockLargeResultJobQuery(StatementType.SELECT, null); + BigQueryStatement jsonStmtSpy = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + Mockito.doAnswer( + invocation -> { + jsonStmtSpy.close(); + return invocation.callRealMethod(); + }) + .when(jsonStmtSpy) + .getEffectiveTotalRows(any(TableResult.class)); + + BigQueryJdbcException jsonEx = + assertThrows(BigQueryJdbcException.class, () -> jsonStmtSpy.executeQuery("SELECT 1")); + assertEquals("Statement was closed.", jsonEx.getMessage()); + assertTrue(jsonStmtSpy.isClosed()); + assertNull(jsonStmtSpy.getResultSet()); + + // 2. Arrow path: Statement.close() lands inside processArrowResultSet before + // getBigQueryReadClient() -> requireOpenConnection() throws "Statement was closed." without + // opening a Storage Read API session or NPE. + Mockito.clearInvocations(bigquery); + doReturn(true).when(bigQueryConnection).isEnableHighThroughputAPI(); + doReturn(100).when(bigQueryConnection).getHighThroughputMinTableSize(); + doReturn(2).when(bigQueryConnection).getHighThroughputActivationRatio(); + BigQueryReadClient readClient = mock(BigQueryReadClient.class); + doReturn(readClient).when(bigQueryConnection).getBigQueryReadClient(); + + Job arrowJob = setupMockLargeResultJobQuery(StatementType.SELECT, null); + TableResult arrowTableResult = arrowJob.getQueryResults(QueryResultsOption.pageSize(1000L)); + doReturn(Schema.of(fieldList)).when(arrowTableResult).getSchema(); + doReturn(2000L).when(arrowTableResult).getTotalRows(); + doReturn(500L).when(arrowTableResult).getRowsInPage(); + doReturn(true).when(arrowTableResult).hasNextPage(); + + BigQueryStatement arrowStmtSpy = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + Mockito.doAnswer( + invocation -> { + arrowStmtSpy.close(); + return TABLE_ID; + }) + .when(arrowStmtSpy) + .getDestinationTable(any()); + + BigQueryJdbcException arrowEx = + assertThrows(BigQueryJdbcException.class, () -> arrowStmtSpy.executeQuery("SELECT 2")); + assertEquals("Statement was closed.", arrowEx.getMessage()); + assertTrue(arrowStmtSpy.isClosed()); + verify(readClient, never()).createReadSession(any(CreateReadSessionRequest.class)); + } + + @Test + public void testStatement_oomDuringResultSetCreationNotSwallowedOnClose() throws Exception { + setupMockQueryResults(JobId.of("oom-job"), StatementType.SELECT, null); + BigQueryStatement stmtSpy = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + OutOfMemoryError oom = new OutOfMemoryError("heap exhausted"); + Mockito.doAnswer( + invocation -> { + stmtSpy.close(); + throw oom; + }) + .when(stmtSpy) + .runNextPageTaskAsync(any(), any(), any(), any(), any()); + + BigQueryJdbcException ex = + assertThrows(BigQueryJdbcException.class, () -> stmtSpy.executeQuery("SELECT 1")); + assertThat(ex.getCause()).isSameInstanceAs(oom); + } + + @Test + public void testStatement_scriptHasNoMoreResultsAfterCancelOrClose() throws Exception { + Job childJob1 = + createScriptChildJobMock( + "script-cancel-child-1", StatementType.SELECT, 1L, 1L, false, null); + Job childJob2 = + createScriptChildJobMock( + "script-cancel-child-2", StatementType.SELECT, 1L, 1L, false, null); + @SuppressWarnings("unchecked") + Page childJobsPage = mock(Page.class); + doReturn(Arrays.asList(childJob2, childJob1)).when(childJobsPage).iterateAll(); + doReturn(childJobsPage).when(bigquery).listJobs(any(JobListOption.class)); + setupMockQueryResults(JobId.of("script-parent-job"), StatementType.SCRIPT, null); + + // 1. After cancel(), both hasMoreResults() and getMoreResults() return false. + try (BigQueryStatement cancelStmt = new BigQueryStatement(bigQueryConnection)) { + assertTrue(cancelStmt.execute("SELECT 1; SELECT 2;")); + assertTrue(cancelStmt.hasMoreResults()); + cancelStmt.cancel(); + assertFalse(cancelStmt.hasMoreResults()); + assertFalse(cancelStmt.getMoreResults()); + } + + // 2. After close(), hasMoreResults() returns false and getNextJob() returns null. + BigQueryStatement closeStmt = new BigQueryStatement(bigQueryConnection); + assertTrue(closeStmt.execute("SELECT 1; SELECT 2;")); + closeStmt.close(); + assertFalse(closeStmt.hasMoreResults()); + assertNull(closeStmt.getNextJob()); + } + + @Test + public void testStatement_nonTerminalQueryWithTimeoutFailureCancelsClientJobId() + throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + + // 1. Non-terminal 503 during queryWithTimeout -> best-effort cancel using client JobId. + doThrow(new BigQueryException(503, "Backend timeout")) + .when(bigquery) + .queryWithTimeout(any(QueryJobConfiguration.class), any(JobId.class), any()); + try (BigQueryStatement stmt = new BigQueryStatement(bigQueryConnection)) { + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + } + ArgumentCaptor nonTerminalJobIdCaptor = ArgumentCaptor.forClass(JobId.class); + verify(bigquery) + .queryWithTimeout( + any(QueryJobConfiguration.class), nonTerminalJobIdCaptor.capture(), any()); + verify(bigquery, times(1)).cancel(eq(nonTerminalJobIdCaptor.getValue())); + + // 2. Terminal 400 during queryWithTimeout -> must NOT call bigquery.cancel(jobId). + Mockito.clearInvocations(bigquery); + doThrow(new BigQueryException(400, "Syntax error: invalid SQL")) + .when(bigquery) + .queryWithTimeout(any(QueryJobConfiguration.class), any(JobId.class), any()); + try (BigQueryStatement stmt = new BigQueryStatement(bigQueryConnection)) { + assertThrows( + BigQueryJdbcSqlSyntaxErrorException.class, () -> stmt.executeQuery("SELECT BAD")); + } + verify(bigquery, never()).cancel(any(JobId.class)); + } }