diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index b11184343536..b75b6efab7da 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -199,7 +199,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `AllowLargeResults` | `true` | Allows large query results (required when using legacy SQL destination tables). | | `LargeResultTable` | `null` | Destination table name for query result sets. When specified, results are written with `WRITE_TRUNCATE`. When omitted while `LargeResultDataset` is set, the driver generates a unique temporary table (`temp_table_`) with `WRITE_EMPTY`. | | `LargeResultDataset` | `null` | Destination dataset name for query result sets. If the dataset does not exist, the driver automatically creates it with creator-only `OWNER` access (omitting default project-wide group ACLs) and a default table expiration of at least 1 hour (`3600000` ms). Multi-process or shared-dataset deployments using non-service-account credentials should pre-create `LargeResultDataset` with the desired ACLs. Under Legacy SQL mode when `LargeResultTable` is set without `LargeResultDataset`, defaults to `_google_jdbc`. | -| `LargeResultsDatasetExpirationTime` | `3600000` (1 hour) | Non-negative expiration time (in milliseconds) for temporary destination tables in auto-created destination datasets (`0` uses the default `3600000` ms; values under 1 hour are clamped to `3600000` ms on auto-created datasets with a warning). | +| `LargeResultsDatasetExpirationTime` | `3600000` (1 hour) | Non-negative expiration time (in milliseconds) for generated temporary destination tables and auto-created destination datasets (`0` uses the default `3600000` ms; values under 1 hour are clamped to `3600000` ms on auto-created datasets with a warning). Pre-existing datasets with a finite `defaultTableLifetime` are respected as configured; when a pre-existing dataset has no `defaultTableLifetime`, per-table expiration is set as a fixed deadline from query completion (increase this value or configure a dataset TTL for reads exceeding 1 hour). | | `KMSKeyName` | `null` | Cloud KMS key resource name used for encrypting query results and destination tables. | ### Session & Transaction Properties diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index d1fd1c25b5cf..d4a17d905f51 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -1277,6 +1277,7 @@ void resetForReuse() throws SQLException { this.clientInfo.clear(); this.sqlWarnings.clear(); this.holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; + this.largeResultDestinations.resetForReuse(); if (exceptionToThrow != null) { throw exceptionToThrow; 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 ea9450674916..2c8dc60e2c1e 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 @@ -309,8 +309,9 @@ private ResultSet executeQueryImpl(String sql) throws SQLException { logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); - jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration); - runQuery(sql, jobConfiguration.build()); + LargeResultDestinations.TempTablePlan tempTablePlan = + configureDestinationDatasetAndTable(jobConfiguration); + runQuery(sql, jobConfiguration.build(), tempTablePlan); checkNotClosedOrCanceled(); if (!isSingularResultSet()) { @@ -370,13 +371,15 @@ private boolean executeImpl(String sql) throws SQLException { logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); + LargeResultDestinations.TempTablePlan tempTablePlan = + LargeResultDestinations.TempTablePlan.NONE; if (isLargeResultsEnabled()) { validateLargeResultsDestinationConfig(); if (getQueryType(jobConfiguration.build(), null) == SqlType.SELECT) { - jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration); + tempTablePlan = configureDestinationDatasetAndTable(jobConfiguration); } } - runQuery(sql, jobConfiguration.build()); + runQuery(sql, jobConfiguration.build(), tempTablePlan); return getCurrentResultSet() != null; } @@ -861,6 +864,14 @@ private StatementType getStatementType(ExecuteResult executeResult) { */ @InternalApi void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLException { + runQuery(query, jobConfiguration, LargeResultDestinations.TempTablePlan.NONE); + } + + private void runQuery( + String query, + QueryJobConfiguration jobConfiguration, + LargeResultDestinations.TempTablePlan tempTablePlan) + throws SQLException { LOG.finer("++enter++"); LOG.fine("Run Query started"); @@ -869,6 +880,8 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx jobConfiguration.toBuilder().setJobTimeoutMs(Long.valueOf(queryTimeout) * 1000).build(); } + TableId executionTempTableId = tempTablePlan.tempTableId; + boolean applyTempTableExpiration = tempTablePlan.needsTableExpiration; boolean executionStarted = false; BigQueryConnection conn = null; @@ -889,6 +902,13 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx } ExecuteResult executeResult = executeJob(jobConfiguration, conn); checkNotClosedOrCanceled(); + if (executionTempTableId != null && applyTempTableExpiration) { + this.largeResultDestinations.applyTempTableExpirationBestEffort( + this.bigQuery, + executionTempTableId, + this.querySettings.getDestinationDatasetExpirationTime()); + checkNotClosedOrCanceled(); + } StatementType statementType = getStatementType(executeResult); this.currentExecutionBuilder.setStatementType( @@ -970,33 +990,41 @@ private void validateLargeResultsDestinationConfig() throws BigQueryJdbcExceptio QueryJobConfiguration.Builder setDestinationDatasetAndTableInJobConfig( QueryJobConfiguration.Builder jobConfigurationBuilder) throws BigQueryJdbcException { + configureDestinationDatasetAndTable(jobConfigurationBuilder); + return jobConfigurationBuilder; + } + + private LargeResultDestinations.TempTablePlan configureDestinationDatasetAndTable( + QueryJobConfiguration.Builder jobConfigurationBuilder) throws BigQueryJdbcException { String configuredDestinationTable = this.querySettings.getDestinationTable(); String destinationDataset = this.querySettings.getDestinationDataset(); if (destinationDataset == null && configuredDestinationTable == null) { - return jobConfigurationBuilder; + return LargeResultDestinations.TempTablePlan.NONE; } validateLargeResultsDestinationConfig(); - if (destinationDataset != null) { - checkIfDatasetExistElseCreate(destinationDataset); - } else { - checkIfDatasetExistElseCreate(DEFAULT_DATASET_NAME); - destinationDataset = DEFAULT_DATASET_NAME; - } + String targetDataset = destinationDataset != null ? destinationDataset : DEFAULT_DATASET_NAME; + boolean needsTableExpiration = ensureDatasetAndCheckNeedsTableExpiration(targetDataset); boolean isGeneratedTempTable = (configuredDestinationTable == null); String targetTableName = isGeneratedTempTable ? getDefaultDestinationTable() : configuredDestinationTable; + TableId targetTableId = TableId.of(targetDataset, targetTableName); JobInfo.WriteDisposition writeDisposition = isGeneratedTempTable ? JobInfo.WriteDisposition.WRITE_EMPTY : JobInfo.WriteDisposition.WRITE_TRUNCATE; - return jobConfigurationBuilder + jobConfigurationBuilder .setAllowLargeResults(this.querySettings.getAllowLargeResults()) - .setDestinationTable(TableId.of(destinationDataset, targetTableName)) + .setDestinationTable(targetTableId) .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) .setWriteDisposition(writeDisposition); + + if (isGeneratedTempTable) { + return new LargeResultDestinations.TempTablePlan(targetTableId, needsTableExpiration); + } + return LargeResultDestinations.TempTablePlan.NONE; } Job getNextJob() { @@ -1927,9 +1955,10 @@ boolean isEnableTimestampPicos() { return this.querySettings.isEnableTimestampPicos(); } - private void checkIfDatasetExistElseCreate(String datasetName) throws BigQueryJdbcException { + private boolean ensureDatasetAndCheckNeedsTableExpiration(String datasetName) + throws BigQueryJdbcException { BigQueryConnection activeConn = requireOpenConnection(); - this.largeResultDestinations.ensureDatasetExists( + return this.largeResultDestinations.ensureDatasetAndCheckNeedsTableExpiration( this.bigQuery, activeConn, datasetName, diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java index 17debc0cdd25..262191b9529e 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java @@ -22,6 +22,9 @@ import com.google.cloud.bigquery.Dataset; import com.google.cloud.bigquery.DatasetId; import com.google.cloud.bigquery.DatasetInfo; +import com.google.cloud.bigquery.StandardTableDefinition; +import com.google.cloud.bigquery.TableId; +import com.google.cloud.bigquery.TableInfo; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import java.net.HttpURLConnection; import java.util.ArrayList; @@ -30,6 +33,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; /** * Coordinates destination dataset provisioning and lifecycle management for {@code @@ -57,6 +61,81 @@ interface AbortCheck { void check() throws BigQueryJdbcException; } + static final class TempTablePlan { + static final TempTablePlan NONE = new TempTablePlan(null, false); + + final TableId tempTableId; + final boolean needsTableExpiration; + + TempTablePlan(TableId tempTableId, boolean needsTableExpiration) { + this.tempTableId = tempTableId; + this.needsTableExpiration = needsTableExpiration; + } + } + + private final AtomicBoolean tempTableUpdateForbidden = new AtomicBoolean(false); + + void resetForReuse() { + this.tempTableUpdateForbidden.set(false); + } + + boolean isTempTableUpdateForbidden() { + return this.tempTableUpdateForbidden.get(); + } + + static boolean needsPerTableExpiration(Dataset dataset) { + if (dataset == null) { + return true; + } + Long datasetDefaultTtlMs = dataset.getDefaultTableLifetime(); + return datasetDefaultTtlMs == null || datasetDefaultTtlMs <= 0; + } + + void applyTempTableExpirationBestEffort(BigQuery bigQuery, TableId tableId, long ttlMs) { + if (this.tempTableUpdateForbidden.get()) { + return; + } + long nowMs = System.currentTimeMillis(); + long expirationTimeMs = (Long.MAX_VALUE - nowMs < ttlMs) ? Long.MAX_VALUE : nowMs + ttlMs; + try { + TableInfo tableInfo = + TableInfo.newBuilder(tableId, StandardTableDefinition.newBuilder().build()) + .setExpirationTime(expirationTimeMs) + .build(); + bigQuery.update(tableInfo); + LOG.fine( + "Set expirationTime=%d on temporary destination table %s.", expirationTimeMs, tableId); + } catch (RuntimeException ex) { + if (isAccessDeniedException(ex)) { + if (this.tempTableUpdateForbidden.compareAndSet(false, true)) { + LOG.warning( + "Permission denied setting expirationTime on temporary destination table %s;" + + " skipping further temp table expiration updates on this connection: %s", + tableId, ex.getMessage()); + } + } else { + LOG.warning( + "Failed to set expirationTime on temporary destination table %s: %s", + tableId, ex.getMessage()); + } + } + } + + static boolean isAccessDeniedException(RuntimeException ex) { + if (!(ex instanceof BigQueryException)) { + return false; + } + BigQueryException bqEx = (BigQueryException) ex; + if (bqEx.getCode() != HttpURLConnection.HTTP_FORBIDDEN) { + return false; + } + String reason = + bqEx.getReason() != null + ? bqEx.getReason() + : (bqEx.getError() != null ? bqEx.getError().getReason() : null); + return "accessDenied".equalsIgnoreCase(reason); + } + private static final class DatasetAclInspection { private final List nonDefaultGroupAcls; private final boolean hasDefaultSpecialGroupAcl; @@ -72,7 +151,7 @@ private DatasetAclInspection( } } - Dataset ensureDatasetExists( + boolean ensureDatasetAndCheckNeedsTableExpiration( BigQuery bigQuery, BigQueryConnection conn, String datasetName, @@ -86,13 +165,14 @@ Dataset ensureDatasetExists( throw new BigQueryJdbcException("Failed to check destination dataset: " + datasetName, ex); } if (dataset != null) { - return dataset; + return needsPerTableExpiration(dataset); } abortCheck.check(); - return createDataset(bigQuery, conn, datasetName, configuredExpirationMs); + return createDatasetAndCheckNeedsTableExpiration( + bigQuery, conn, datasetName, configuredExpirationMs); } - private Dataset createDataset( + private boolean createDatasetAndCheckNeedsTableExpiration( BigQuery bigQuery, BigQueryConnection conn, String datasetName, long configuredExpirationMs) throws BigQueryJdbcException { String sanitizedDatasetName = BigQueryConnection.sanitizeForLog(datasetName); @@ -123,17 +203,19 @@ private Dataset createDataset( createdDataset = bigQuery.create(datasetInfoBuilder.build()); } catch (BigQueryException ex) { if (isDatasetConflict(ex)) { - return handleDatasetCreationConflict(bigQuery, datasetName, ownerEmail); + Dataset existingDataset = handleDatasetCreationConflict(bigQuery, datasetName, ownerEmail); + return needsPerTableExpiration(existingDataset); } throw new BigQueryJdbcException("Failed to create destination dataset: " + datasetName, ex); } if (ownerEmail != null) { - return createdDataset; + return false; } try { - return restrictAutoCreatedDatasetAclToCreator(bigQuery, datasetName, createdDataset); + restrictAutoCreatedDatasetAclToCreator(bigQuery, datasetName, createdDataset); + return false; } catch (BigQueryJdbcException ex) { deleteEmptyDatasetBestEffort(bigQuery, datasetName); throw ex; @@ -198,7 +280,7 @@ private static DatasetAclInspection inspectDatasetAcl(List currentAcl) { * datasets.patch} before any query job writes to the dataset, failing closed if an explicit * creator {@code OWNER} entry cannot be verified. */ - private Dataset restrictAutoCreatedDatasetAclToCreator( + private void restrictAutoCreatedDatasetAclToCreator( BigQuery bigQuery, String datasetName, Dataset createdDataset) throws BigQueryJdbcException { if (createdDataset == null || createdDataset.getAcl() == null) { throw new BigQueryJdbcException( @@ -211,10 +293,10 @@ private Dataset restrictAutoCreatedDatasetAclToCreator( + datasetName); } if (!inspection.hasDefaultSpecialGroupAcl) { - return createdDataset; + return; } try { - return bigQuery.update( + bigQuery.update( DatasetInfo.newBuilder(datasetName).setAcl(inspection.nonDefaultGroupAcls).build()); } catch (BigQueryException ex) { throw new BigQueryJdbcException( 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 0acebaf706b0..9c040b3410ce 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 @@ -49,6 +49,7 @@ import com.google.cloud.bigquery.BigQuery.JobListOption; import com.google.cloud.bigquery.BigQuery.QueryResultsOption; import com.google.cloud.bigquery.BigQuery.TableDataListOption; +import com.google.cloud.bigquery.BigQueryError; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.Dataset; @@ -71,6 +72,7 @@ import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.TableId; +import com.google.cloud.bigquery.TableInfo; import com.google.cloud.bigquery.TableResult; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcSqlSyntaxErrorException; @@ -2163,6 +2165,7 @@ public void testLargeResultTable_explicitTableUsesWriteTruncate() throws Excepti assertEquals(JobInfo.WriteDisposition.WRITE_TRUNCATE, capturedConfig.getWriteDisposition()); assertNotNull(jobIdCaptor.getValue().getJob()); assertTrue(jobIdCaptor.getValue().getJob().startsWith("google-jdbc-")); + verify(bigquery, never()).update(any(TableInfo.class)); } @Test @@ -2438,20 +2441,22 @@ public void testStatement_concurrentCloseBeforeRunQueryAbortsWithoutSubmittingJo } } - @Test - public void testStatement_concurrentCloseDuringGetJobThrowsClosedNoNpe() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testStatement_concurrentCloseDuringGetJobOrTableExpirationThrowsClosedNoNpe( + boolean closeDuringGetJob) 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))); + Dataset datasetWithoutTtl = mock(Dataset.class); + doReturn(null).when(datasetWithoutTtl).getDefaultTableLifetime(); + doReturn(datasetWithoutTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); StubbedLargeResultJob stubbedJob = createStubbedLargeResultJob(StatementType.SELECT, null); Map jobsById = new ConcurrentHashMap<>(); - CountDownLatch enteredGetJob = new CountDownLatch(1); + CountDownLatch enteredTargetRpc = new CountDownLatch(1); CountDownLatch closeFinished = new CountDownLatch(1); Mockito.doAnswer( @@ -2466,18 +2471,30 @@ public void testStatement_concurrentCloseDuringGetJobThrowsClosedNoNpe() throws .queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); Mockito.doAnswer( invocation -> { - enteredGetJob.countDown(); - assertTrue(closeFinished.await(5, TimeUnit.SECONDS)); + if (closeDuringGetJob) { + enteredTargetRpc.countDown(); + assertTrue(closeFinished.await(5, TimeUnit.SECONDS)); + } return jobsById.get(invocation.getArgument(0)); }) .when(bigquery) .getJob(any(JobId.class)); + if (!closeDuringGetJob) { + Mockito.doAnswer( + invocation -> { + enteredTargetRpc.countDown(); + assertTrue(closeFinished.await(5, TimeUnit.SECONDS)); + return null; + }) + .when(bigquery) + .update(any(TableInfo.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)); + assertTrue(enteredTargetRpc.await(5, TimeUnit.SECONDS)); stmt.close(); closeFinished.countDown(); @@ -2486,9 +2503,13 @@ public void testStatement_concurrentCloseDuringGetJobThrowsClosedNoNpe() throws 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()); + if (closeDuringGetJob) { + verify(bigquery, never()).update(any(TableInfo.class)); + } else { + verify(bigquery, times(1)).update(any(TableInfo.class)); + } } finally { callerPool.shutdownNow(); } @@ -2708,6 +2729,7 @@ public void testAutoCreatedDataset_serviceAccountAtomicOwnerAclAndSubHourClamp( Collections.singletonList(Acl.of(new Acl.User(expectedOwnerEmail), Acl.Role.OWNER)), createdDataset.getAcl()); verify(bigquery, never()).update(any(DatasetInfo.class)); + verify(bigquery, never()).update(any(TableInfo.class)); } @Test @@ -2824,7 +2846,7 @@ public void testAutoCreatedDataset_conflictRaceAndDatasetRpcErrors() throws Exce .toString(); setupMockLargeResultJobQuery(StatementType.SELECT, null); - // 1. 409 Conflict where reload succeeds -> proceeds with query. + // 1. 409 Conflict where reload succeeds with finite TTL -> proceeds without tables.update. Dataset reloadedWithTtl = mock(Dataset.class); doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(reloadedWithTtl).getDefaultTableLifetime(); Mockito.when(bigquery.getDataset(eq(DatasetId.of(datasetName)))) @@ -2839,6 +2861,24 @@ public void testAutoCreatedDataset_conflictRaceAndDatasetRpcErrors() throws Exce ResultSet rs = stmt.executeQuery("SELECT 1")) { assertNotNull(rs); } + verify(bigquery, never()).update(any(TableInfo.class)); + + // 1b. 409 Conflict where reload fails for SA -> proceeds and falls back to per-table TTL. + Mockito.reset(bigquery); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + Mockito.when(bigquery.getDataset(eq(DatasetId.of(datasetName)))) + .thenReturn(null) + .thenThrow(new BigQueryException(503, "Reload failed")); + doThrow(new BigQueryException(409, "Already Exists")) + .when(bigquery) + .create(any(DatasetInfo.class)); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + verify(bigquery, times(1)).update(any(TableInfo.class)); // 2. Non-409 BigQueryException on dataset create -> wrapped as BigQueryJdbcException. Mockito.reset(bigquery); @@ -3019,4 +3059,146 @@ public void testAutoCreatedDataset_concurrentCancelDuringDatasetCheckAbortsWitho callerPool.shutdownNow(); } } + + private static Stream perTableExpirationCases() { + return Stream.of( + Arguments.of("null_ttl_uses_default_1h", null, null, DEFAULT_DATASET_EXPIRATION_MS), + Arguments.of("zero_ttl_uses_default_1h", 0L, null, DEFAULT_DATASET_EXPIRATION_MS), + Arguments.of( + "zero_url_expiration_falls_back_to_1h", null, "0", DEFAULT_DATASET_EXPIRATION_MS), + Arguments.of("null_ttl_uses_configured_4h", null, "14400000", 14_400_000L), + Arguments.of( + "finite_dataset_ttl_preserved_over_url_setting", 86_400_000L, "3600000", null)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("perTableExpirationCases") + public void testLargeResultDataset_perTableExpirationAppliedOnlyWhenDatasetHasNoDefaultTtl( + String caseName, Long datasetDefaultTtlMs, String urlExpirationMs, Long expectedPerTableTtlMs) + throws Exception { + String url = + urlExpirationMs != null + ? BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .append("LargeResultsDatasetExpirationTime", urlExpirationMs) + .toString() + : BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .toString(); + Dataset existingDataset = mock(Dataset.class); + doReturn(datasetDefaultTtlMs).when(existingDataset).getDefaultTableLifetime(); + doReturn(existingDataset).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + long beforeMs = System.currentTimeMillis(); + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + long afterMs = System.currentTimeMillis(); + + if (expectedPerTableTtlMs == null) { + verify(bigquery, never()).update(any(TableInfo.class)); + return; + } + + ArgumentCaptor configCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(bigquery).queryWithTimeout(configCaptor.capture(), any(), any()); + ArgumentCaptor updateCaptor = ArgumentCaptor.forClass(TableInfo.class); + verify(bigquery, times(1)).update(updateCaptor.capture()); + TableInfo patchedTable = updateCaptor.getValue(); + assertEquals(configCaptor.getValue().getDestinationTable(), patchedTable.getTableId()); + assertNotNull(patchedTable.getExpirationTime()); + assertTrue(patchedTable.getExpirationTime() >= beforeMs + expectedPerTableTtlMs); + assertTrue(patchedTable.getExpirationTime() <= afterMs + expectedPerTableTtlMs); + } + + @Test + public void testLargeResultDataset_memoizes403OnTableUpdateAndResetsForReuse() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .toString(); + Dataset datasetWithoutTtl = mock(Dataset.class); + doReturn(null).when(datasetWithoutTtl).getDefaultTableLifetime(); + doReturn(datasetWithoutTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + doThrow( + new BigQueryException( + 403, "Access Denied", new BigQueryError("accessDenied", "global", "Access Denied"))) + .when(bigquery) + .update(any(TableInfo.class)); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url)) { + try (Statement stmt = conn.createStatement(); + ResultSet rs1 = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs1); + } + assertTrue(conn.getLargeResultDestinations().isTempTableUpdateForbidden()); + + // Second query on the same connection skips tables.update. + try (Statement stmt = conn.createStatement(); + ResultSet rs2 = stmt.executeQuery("SELECT 2")) { + assertNotNull(rs2); + } + verify(bigquery, times(1)).update(any(TableInfo.class)); + + // Pooled connection reset clears the memoized 403 flag. + conn.resetForReuse(); + assertFalse(conn.getLargeResultDestinations().isTempTableUpdateForbidden()); + + try (Statement stmt = conn.createStatement(); + ResultSet rs3 = stmt.executeQuery("SELECT 3")) { + assertNotNull(rs3); + } + verify(bigquery, times(2)).update(any(TableInfo.class)); + } + } + + private static Stream nonAccessDeniedTableUpdateErrors() { + return Stream.of( + Arguments.of( + "http_503_backend_error", + new BigQueryException( + 503, "Backend error", new BigQueryError("backendError", "global", "Backend"))), + Arguments.of( + "http_403_rate_limit_exceeded", + new BigQueryException( + 403, + "Rate Limit Exceeded", + new BigQueryError("rateLimitExceeded", "usageLimits", "Rate limit")))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("nonAccessDeniedTableUpdateErrors") + public void testLargeResultDataset_nonAccessDeniedUpdateFailureDoesNotPoisonConnection( + String caseName, BigQueryException updateError) throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .toString(); + Dataset datasetWithoutTtl = mock(Dataset.class); + doReturn(null).when(datasetWithoutTtl).getDefaultTableLifetime(); + doReturn(datasetWithoutTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + doThrow(updateError).when(bigquery).update(any(TableInfo.class)); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + try (ResultSet rs1 = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs1); + } + try (ResultSet rs2 = stmt.executeQuery("SELECT 2")) { + assertNotNull(rs2); + } + assertFalse(conn.getLargeResultDestinations().isTempTableUpdateForbidden()); + } + verify(bigquery, times(2)).update(any(TableInfo.class)); + } }