From 9db511aacbcdd2d9dc6c0fde1efee9500b95e04e Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Tue, 1 Dec 2026 17:03:08 +0000 Subject: [PATCH] fix(bigquery-jdbc): validate LargeResult properties and use UUID temp tables with WRITE_EMPTY --- java-bigquery-jdbc/docs/USER_GUIDE.md | 6 +- .../cloud/bigquery/jdbc/BigQuerySettings.java | 2 + .../bigquery/jdbc/BigQueryStatement.java | 95 ++++--- .../cloud/bigquery/jdbc/DataSource.java | 3 + .../bigquery/jdbc/BigQueryStatementTest.java | 246 ++++++++++++++++++ .../cloud/bigquery/jdbc/DataSourceTest.java | 55 ++++ 6 files changed, 369 insertions(+), 38 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index cb2f7cc28e92..cc12bb2079bc 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -197,9 +197,9 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `JobCreationMode` | `2` | Job creation strategy: `1` (`JOB_CREATION_REQUIRED` - forces explicit query job creation for every query) or `2` (`JOB_CREATION_OPTIONAL` - default, allows queries to execute directly without creating explicit jobs when possible). | | `MaxResults` | `10000` | Maximum number of rows returned per page during standard REST result set iteration. | | `AllowLargeResults` | `true` | Allows large query results (required when using legacy SQL destination tables). | -| `LargeResultTable` | `null` | Destination table name for query result sets. If omitted when `LargeResultDataset` is set, the driver automatically generates a temporary table name (`_jdbc_tmp_`). | -| `LargeResultDataset` | `null` | Destination dataset name for query result sets. If the specified dataset does not exist, the driver automatically creates it. Under Legacy SQL mode, defaults to creating/using `_jdbc_tmp`. | -| `LargeResultsDatasetExpirationTime` | `3600000` (1 hour) | Expiration time (in milliseconds) for temporary destination tables in user-specified datasets. | +| `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 specified dataset does not exist, the driver automatically creates it. 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). | | `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/BigQuerySettings.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQuerySettings.java index bc1b932022f5..215209fc0c9d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQuerySettings.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQuerySettings.java @@ -565,6 +565,8 @@ private Builder(BigQuerySettings querySettings) { Builder withDefaultValues() { return setUseReadAPI(false) // Read API is disabled by default; .setQueryDialect(BigQueryJdbcUrlUtility.DEFAULT_QUERY_DIALECT_VALUE) + .setDestinationDatasetExpirationTime( + BigQueryJdbcUrlUtility.DEFAULT_DESTINATION_DATASET_EXPIRATION_TIME_VALUE) .setNumBufferedRows( DEFAULT_NUM_BUFFERED_ROWS) // 10K records will be kept in the buffer (Blocking Queue); .setMaxResultPerPage(BigQueryJdbcUrlUtility.DEFAULT_MAX_RESULTS_VALUE); 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 b60fb26c9fe9..5e6041717c36 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 @@ -77,14 +77,12 @@ import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; -import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; @@ -258,11 +256,15 @@ private BigQuerySettings generateBigQuerySettings() throws SQLException { if (this.connection.getJobTimeoutInSeconds() > 0) { querySettings.setJobTimeoutMs(this.connection.getJobTimeoutInSeconds() * 1000L); } - if (this.connection.getDestinationTable() != null) { - querySettings.setDestinationTable(this.connection.getDestinationTable()); + if (!isInternal()) { + if (this.connection.getDestinationTable() != null) { + querySettings.setDestinationTable(this.connection.getDestinationTable()); + } + if (this.connection.getDestinationDataset() != null) { + querySettings.setDestinationDataset(this.connection.getDestinationDataset()); + } } - if (this.connection.getDestinationDataset() != null) { - querySettings.setDestinationDataset(this.connection.getDestinationDataset()); + if (this.connection.getDestinationDatasetExpirationTime() > 0) { querySettings.setDestinationDatasetExpirationTime( this.connection.getDestinationDatasetExpirationTime()); } @@ -365,8 +367,11 @@ private boolean executeImpl(String sql) throws SQLException { logQueryExecutionStart(sql); QueryJobConfiguration.Builder jobConfiguration = getJobConfig(sql); jobConfiguration = applyParametersIfPresent(jobConfiguration); - if (isLargeResultsEnabled() && getQueryType(jobConfiguration.build(), null) == SqlType.SELECT) { - jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration); + if (isLargeResultsEnabled()) { + validateLargeResultsDestinationConfig(); + if (getQueryType(jobConfiguration.build(), null) == SqlType.SELECT) { + jobConfiguration = setDestinationDatasetAndTableInJobConfig(jobConfiguration); + } } runQuery(sql, jobConfiguration.build()); return getCurrentResultSet() != null; @@ -625,10 +630,14 @@ ExecuteResult executeJob(QueryJobConfiguration jobConfiguration) throws InterruptedException, BigQueryException, BigQueryJdbcException { LOG.finer("++enter++"); Job job = null; - // Location is not properly passed from the connection, - // so we need to explicitly set it; - // Do not set custom JobId here or it will disable jobless queries. - JobId jobId = JobId.newBuilder().setLocation(connection.getLocation()).build(); + // 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()); + if (jobConfiguration.getDestinationTable() != null) { + jobIdBuilder.setJob(generateJobId()); + } + JobId jobId = jobIdBuilder.build(); Object result = bigQuery.queryWithTimeout(jobConfiguration, jobId, null); if (result instanceof TableResult) { TableResult tableResult = (TableResult) result; @@ -781,28 +790,44 @@ boolean isLargeResultsEnabled() { return destinationDataset != null || destinationTable != null; } + private void validateLargeResultsDestinationConfig() throws BigQueryJdbcException { + if (this.querySettings.getDestinationDataset() == null + && this.querySettings.getDestinationTable() != null + && !getUseLegacySql()) { + throw new BigQueryJdbcException( + "LargeResultDataset must be specified when LargeResultTable is set with Standard SQL."); + } + } + QueryJobConfiguration.Builder setDestinationDatasetAndTableInJobConfig( QueryJobConfiguration.Builder jobConfigurationBuilder) throws BigQueryJdbcException { - String destinationTable = this.querySettings.getDestinationTable(); + String configuredDestinationTable = this.querySettings.getDestinationTable(); String destinationDataset = this.querySettings.getDestinationDataset(); - if (destinationDataset != null || destinationTable != null) { - if (destinationDataset != null) { - checkIfDatasetExistElseCreate(destinationDataset); - } - if (getUseLegacySql() && destinationDataset == null) { - checkIfDatasetExistElseCreate(DEFAULT_DATASET_NAME); - destinationDataset = DEFAULT_DATASET_NAME; - } - if (destinationTable == null) { - destinationTable = getDefaultDestinationTable(); - } - return jobConfigurationBuilder - .setAllowLargeResults(this.querySettings.getAllowLargeResults()) - .setDestinationTable(TableId.of(destinationDataset, destinationTable)) - .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) - .setWriteDisposition(JobInfo.WriteDisposition.WRITE_TRUNCATE); + if (destinationDataset == null && configuredDestinationTable == null) { + return jobConfigurationBuilder; } - return jobConfigurationBuilder; + + validateLargeResultsDestinationConfig(); + if (destinationDataset != null) { + checkIfDatasetExistElseCreate(destinationDataset); + } else { + checkIfDatasetExistElseCreate(DEFAULT_DATASET_NAME); + destinationDataset = DEFAULT_DATASET_NAME; + } + + boolean isGeneratedTempTable = (configuredDestinationTable == null); + String targetTableName = + isGeneratedTempTable ? getDefaultDestinationTable() : configuredDestinationTable; + JobInfo.WriteDisposition writeDisposition = + isGeneratedTempTable + ? JobInfo.WriteDisposition.WRITE_EMPTY + : JobInfo.WriteDisposition.WRITE_TRUNCATE; + + return jobConfigurationBuilder + .setAllowLargeResults(this.querySettings.getAllowLargeResults()) + .setDestinationTable(TableId.of(destinationDataset, targetTableName)) + .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) + .setWriteDisposition(writeDisposition); } Job getNextJob() { @@ -1713,9 +1738,7 @@ private void checkIfDatasetExistElseCreate(String datasetName) throws BigQueryJd } private String getDefaultDestinationTable() { - String timeOfCreation = String.valueOf(Instant.now().toEpochMilli()); - String randomizedId = String.valueOf(new Random().nextInt(9999)); - return DEFAULT_TABLE_NAME + timeOfCreation + randomizedId; + return DEFAULT_TABLE_NAME + UUID.randomUUID().toString().replace("-", "_"); } @InternalApi @@ -1992,8 +2015,10 @@ protected void logQueryExecutionStart(String sql) { return; } String truncatedSql = truncateQuery(sql); - LOG.info("Executing query: " + truncatedSql); - LOG.info("Using query settings: " + this.querySettings.toString()); + LOG.info("Executing query: %s", truncatedSql); + LOG.info( + "Using query settings: %s", + BigQueryConnection.sanitizeForLog(this.querySettings.toString())); } private String truncateQuery(String sql) { diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java index 61f5ac9f581a..ee528fa285c3 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -1168,6 +1168,9 @@ public void setDestinationDataset(String destinationDataset) { } public void setDestinationDatasetExpirationTime(long destinationDatasetExpirationTime) { + validateNonNegative( + destinationDatasetExpirationTime, + BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME); this.destinationDatasetExpirationTime = destinationDatasetExpirationTime; } 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 ecbc1a4522fc..244852e166e5 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 @@ -20,6 +20,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -30,6 +31,8 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.withSettings; @@ -46,6 +49,7 @@ import com.google.cloud.bigquery.BigQuery.TableDataListOption; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.Dataset; import com.google.cloud.bigquery.DatasetId; import com.google.cloud.bigquery.DatasetInfo; import com.google.cloud.bigquery.Field; @@ -93,6 +97,7 @@ import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -102,6 +107,7 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -110,6 +116,8 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; import java.util.stream.Stream; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.BitVector; @@ -1966,4 +1974,242 @@ private static void assertFeatureRecorded( private interface SqlRunnable { void run() throws SQLException; } + + private static final Pattern GENERATED_TEMP_TABLE_PATTERN = + Pattern.compile("^temp_table_[0-9a-f]{8}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{12}$"); + private static final String SCRATCH_DATASET = "scratch_dataset"; + private static final long DEFAULT_DATASET_EXPIRATION_MS = + BigQueryJdbcUrlUtility.DEFAULT_DESTINATION_DATASET_EXPIRATION_TIME_VALUE; + + private void configureLargeResults( + String datasetName, String tableName, long expirationMs, Long existingDatasetDefaultTtlMs) { + doReturn(true).when(bigQueryConnection).isAllowLargeResults(); + doReturn(datasetName).when(bigQueryConnection).getDestinationDataset(); + doReturn(tableName).when(bigQueryConnection).getDestinationTable(); + doReturn(expirationMs).when(bigQueryConnection).getDestinationDatasetExpirationTime(); + Dataset dataset = mock(Dataset.class); + doReturn(existingDatasetDefaultTtlMs).when(dataset).getDefaultTableLifetime(); + doReturn(dataset).when(bigquery).getDataset(eq(DatasetId.of(datasetName))); + } + + private static final class StubbedLargeResultJob { + private final Job job; + private final AtomicReference jobIdRef; + private final AtomicReference configRef; + + private StubbedLargeResultJob( + Job job, + AtomicReference jobIdRef, + AtomicReference configRef) { + this.job = job; + this.jobIdRef = jobIdRef; + this.configRef = configRef; + } + + private void bind(QueryJobConfiguration config, JobId effectiveJobId) { + this.jobIdRef.set(effectiveJobId); + this.configRef.set(config); + } + } + + private StubbedLargeResultJob createStubbedLargeResultJob( + StatementType type, Long dmlAffectedRows) throws Exception { + AtomicReference jobIdRef = new AtomicReference<>(); + AtomicReference configRef = new AtomicReference<>(); + + Job jobMock = mock(Job.class); + QueryStatistics statistics = mock(QueryStatistics.class); + doReturn(statistics).when(jobMock).getStatistics(); + doReturn(type).when(statistics).getStatementType(); + if (dmlAffectedRows != null) { + doReturn(dmlAffectedRows).when(statistics).getNumDmlAffectedRows(); + } + TableResult tableResultMock = mock(TableResult.class); + doReturn(Schema.of()).when(tableResultMock).getSchema(); + doReturn(type).when(tableResultMock).getStatementType(); + if (dmlAffectedRows != null) { + doReturn(dmlAffectedRows).when(tableResultMock).getNumDmlAffectedRows(); + } + Mockito.doAnswer(invocation -> jobIdRef.get()).when(tableResultMock).getJobId(); + Mockito.doAnswer(invocation -> jobIdRef.get()).when(jobMock).getJobId(); + Mockito.doAnswer(invocation -> configRef.get()).when(jobMock).getConfiguration(); + doReturn(tableResultMock).when(jobMock).getQueryResults(any(QueryResultsOption.class)); + doReturn(jobMock).when(jobMock).waitFor(); + return new StubbedLargeResultJob(jobMock, jobIdRef, configRef); + } + + private Job setupMockLargeResultJobQuery(StatementType type, Long dmlAffectedRows) + throws Exception { + StubbedLargeResultJob stubbedJob = createStubbedLargeResultJob(type, dmlAffectedRows); + Map jobsById = new ConcurrentHashMap<>(); + Mockito.doAnswer(invocation -> jobsById.get(invocation.getArgument(0))) + .when(bigquery) + .getJob(any(JobId.class)); + + Mockito.doAnswer( + invocation -> { + QueryJobConfiguration config = invocation.getArgument(0); + JobId submittedJobId = invocation.getArgument(1); + JobId effectiveJobId = + submittedJobId != null && submittedJobId.getJob() != null + ? submittedJobId + : JobId.of("server-generated-" + UUID.randomUUID()); + stubbedJob.bind(config, effectiveJobId); + jobsById.put(effectiveJobId, stubbedJob.job); + return stubbedJob.job; + }) + .when(bigquery) + .queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + + Job dryRunJobMock = getJobMock(null, null, type); + doReturn(dryRunJobMock).when(bigquery).create(any(JobInfo.class)); + return stubbedJob.job; + } + + private BigQueryConnection createConnectionWithMockedBigQuery(String url) throws SQLException { + BigQueryConnection conn = new BigQueryConnection(url); + conn.bigQuery = this.bigquery; + return conn; + } + + @Test + public void testLargeResultDataset_usesUuidNameWriteEmptyAndClientJobId() throws Exception { + // 1. Without destinationTable, executeJob must leave JobId.job unset so jobless fast-query + // remains eligible. + setupMockQueryResults(null, StatementType.SELECT, null); + try (BigQueryStatement joblessStmt = new BigQueryStatement(bigQueryConnection); + ResultSet rs = joblessStmt.executeQuery("SELECT 0")) { + assertNotNull(rs); + } + ArgumentCaptor joblessIdCaptor = ArgumentCaptor.forClass(JobId.class); + verify(bigquery) + .queryWithTimeout(any(QueryJobConfiguration.class), joblessIdCaptor.capture(), any()); + assertNull(joblessIdCaptor.getValue().getJob()); + + // 2. With LargeResultDataset, executeJob takes the Job path with a client JobId so + // WRITE_EMPTY retries are idempotent. + Mockito.clearInvocations(bigquery); + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + try (BigQueryStatement statement = new BigQueryStatement(bigQueryConnection)) { + try (ResultSet rs1 = statement.executeQuery("SELECT 1")) { + assertNotNull(rs1); + } + assertTrue(statement.execute("SELECT 2")); + try (ResultSet rs2 = statement.getResultSet()) { + assertNotNull(rs2); + } + } + + ArgumentCaptor configCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + ArgumentCaptor jobIdCaptor = ArgumentCaptor.forClass(JobId.class); + verify(bigquery, times(2)) + .queryWithTimeout(configCaptor.capture(), jobIdCaptor.capture(), any()); + List configs = configCaptor.getAllValues(); + List jobIds = jobIdCaptor.getAllValues(); + + for (int i = 0; i < configs.size(); i++) { + QueryJobConfiguration config = configs.get(i); + assertEquals(SCRATCH_DATASET, config.getDestinationTable().getDataset()); + assertTrue( + GENERATED_TEMP_TABLE_PATTERN.matcher(config.getDestinationTable().getTable()).matches()); + assertEquals(JobInfo.WriteDisposition.WRITE_EMPTY, config.getWriteDisposition()); + assertEquals(JobInfo.CreateDisposition.CREATE_IF_NEEDED, config.getCreateDisposition()); + assertNotNull(jobIds.get(i).getJob()); + assertTrue(jobIds.get(i).getJob().startsWith("google-jdbc-")); + } + assertNotEquals( + configs.get(0).getDestinationTable().getTable(), + configs.get(1).getDestinationTable().getTable()); + assertNotEquals(jobIds.get(0).getJob(), jobIds.get(1).getJob()); + } + + @Test + public void testLargeResultTable_explicitTableUsesWriteTruncate() throws Exception { + configureLargeResults( + SCRATCH_DATASET, "explicit_results_table", DEFAULT_DATASET_EXPIRATION_MS, null); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + try (BigQueryStatement statement = new BigQueryStatement(bigQueryConnection); + ResultSet rs = statement.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + + ArgumentCaptor captor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + ArgumentCaptor jobIdCaptor = ArgumentCaptor.forClass(JobId.class); + verify(bigquery).queryWithTimeout(captor.capture(), jobIdCaptor.capture(), any()); + QueryJobConfiguration capturedConfig = captor.getValue(); + assertEquals( + TableId.of(SCRATCH_DATASET, "explicit_results_table"), + capturedConfig.getDestinationTable()); + assertEquals(JobInfo.WriteDisposition.WRITE_TRUNCATE, capturedConfig.getWriteDisposition()); + assertNotNull(jobIdCaptor.getValue().getJob()); + assertTrue(jobIdCaptor.getValue().getJob().startsWith("google-jdbc-")); + } + + @Test + public void testInternalStatement_ignoresLargeResultDatasetAndLargeResultTable() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", SCRATCH_DATASET) + .append("LargeResultTable", "explicit_user_table") + .toString(); + TableResult validResult = setupMockQueryResults(null, StatementType.SELECT, null); + FieldList oneIntField = FieldList.of(Field.of("f0_", StandardSQLTypeName.INT64)); + FieldValueList oneRow = + FieldValueList.of( + Collections.singletonList(FieldValue.of(FieldValue.Attribute.PRIMITIVE, "1")), + oneIntField); + doReturn(Schema.of(oneIntField)).when(validResult).getSchema(); + doReturn(1L).when(validResult).getTotalRows(); + doReturn(1L).when(validResult).getRowsInPage(); + doReturn(Collections.singletonList(oneRow)).when(validResult).getValues(); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url)) { + assertTrue(conn.isValid(5)); + try (BigQueryStatement internalStmt = conn.createStatementInternal(); + ResultSet rs = internalStmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + } + + verify(bigquery, never()).getDataset(any(DatasetId.class)); + ArgumentCaptor configCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + ArgumentCaptor jobIdCaptor = ArgumentCaptor.forClass(JobId.class); + verify(bigquery, times(2)) + .queryWithTimeout(configCaptor.capture(), jobIdCaptor.capture(), any()); + for (int i = 0; i < 2; i++) { + assertNull(configCaptor.getAllValues().get(i).getDestinationTable()); + assertNull(jobIdCaptor.getAllValues().get(i).getJob()); + } + } + + @Test + public void testLargeResultTable_withoutLargeResultDatasetUnderStandardSqlThrowsJdbcException() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultTable", "explicit_only_table") + .toString(); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + BigQueryJdbcException queryEx = + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + assertThat(queryEx.getMessage()).contains("LargeResultDataset"); + BigQueryJdbcException executeEx = + assertThrows(BigQueryJdbcException.class, () -> stmt.execute("SELECT 1")); + assertThat(executeEx.getMessage()).contains("LargeResultDataset"); + } + verify(bigquery, never()).create(any(JobInfo.class)); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java index 32ddd7292d0e..0220b2de7f0c 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java @@ -27,12 +27,20 @@ import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; +import java.sql.DriverManager; import java.sql.SQLException; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.MockedStatic; public class DataSourceTest { + private static URIBuilder baseUrl() { + return BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project"); + } + @Test public void testWrapperMethods() throws SQLException { DataSource dataSource = new DataSource(); @@ -138,4 +146,51 @@ public void testNormalizeUniverseDomain() { "custom-universe.example.com", BigQueryJdbcUrlUtility.resolveEnvUniverseDomain(" custom-universe.example.com ")); } + + @ParameterizedTest + @ValueSource(longs = {-1L, -3_600_000L}) + public void testDestinationDatasetExpirationTimeRejectsNegativeValues(long invalidValue) { + DataSource ds = new DataSource(); + BigQueryJdbcRuntimeException setterEx = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> ds.setDestinationDatasetExpirationTime(invalidValue)); + assertTrue( + setterEx + .getMessage() + .contains( + "Invalid value for LargeResultsDatasetExpirationTime. It must be greater than or" + + " equal to 0.")); + + String invalidUrl = + baseUrl().append("LargeResultsDatasetExpirationTime", invalidValue).toString(); + BigQueryJdbcRuntimeException urlEx = + assertThrows(BigQueryJdbcRuntimeException.class, () -> DataSource.fromUrl(invalidUrl)); + assertTrue( + urlEx + .getMessage() + .contains( + "Invalid value for LargeResultsDatasetExpirationTime. It must be greater than or" + + " equal to 0.")); + + BigQueryJdbcException driverEx = + assertThrows(BigQueryJdbcException.class, () -> DriverManager.getConnection(invalidUrl)); + assertTrue( + driverEx + .getMessage() + .contains( + "Invalid value for LargeResultsDatasetExpirationTime. It must be greater than or" + + " equal to 0.")); + } + + @Test + public void testDestinationDatasetExpirationTimeAllowsZeroForCompatibility() { + DataSource ds = new DataSource(); + ds.setDestinationDatasetExpirationTime(0L); + assertEquals(0L, ds.getDestinationDatasetExpirationTime()); + + String zeroUrl = baseUrl().append("LargeResultsDatasetExpirationTime", 0L).toString(); + DataSource parsed = DataSource.fromUrl(zeroUrl); + assertEquals(0L, parsed.getDestinationDatasetExpirationTime()); + } }