Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions java-bigquery-jdbc/docs/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,8 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
| `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. When specified, results are written with `WRITE_TRUNCATE`. When omitted while `LargeResultDataset` is set, the driver generates a unique temporary table (`temp_table_<epochMs>_<uuid>`) 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). |
| `LargeResultDataset` | `null` | Destination dataset name for query result sets. If the specified dataset does not exist, the driver automatically creates it with a default table expiration of at least 1 hour (`3600000` ms). 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; positive values under 1 hour are clamped to `3600000` ms with a warning). |
| `KMSKeyName` | `null` | Cloud KMS key resource name used for encrypting query results and destination tables. |

### Session & Transaction Properties
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ protected boolean removeEldestEntry(Map.Entry<String, Map<String, String>> eldes
static final String DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME =
"LargeResultsDatasetExpirationTime";
static final long DEFAULT_DESTINATION_DATASET_EXPIRATION_TIME_VALUE = 3600000L;
static final long MIN_DESTINATION_DATASET_EXPIRATION_TIME_VALUE = 3600000L;
static final boolean DEFAULT_ALLOW_LARGE_RESULTS = true;
static final String QUERY_DIALECT_PROPERTY_NAME = "QueryDialect";
static final String DEFAULT_QUERY_DIALECT_VALUE = "SQL";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1729,17 +1730,37 @@ boolean isEnableTimestampPicos() {
}

private void checkIfDatasetExistElseCreate(String datasetName) throws BigQueryJdbcException {
Dataset dataset = bigQuery.getDataset(DatasetId.of(datasetName));
if (dataset == null) {
LOG.info("Creating a hidden dataset: %s ", datasetName);
DatasetInfo.Builder datasetInfoBuilder =
DatasetInfo.newBuilder(datasetName)
.setDefaultTableLifetime(this.querySettings.getDestinationDatasetExpirationTime());
String location = this.connection.getLocation();
if (location != null && !location.isEmpty()) {
datasetInfoBuilder.setLocation(location);
Dataset dataset;
try {
dataset = this.bigQuery.getDataset(DatasetId.of(datasetName));
} catch (BigQueryException ex) {
throw new BigQueryJdbcException("Failed to check destination dataset: " + datasetName, ex);
}
if (dataset != null) {
return;
}

String sanitizedDatasetName = BigQueryConnection.sanitizeForLog(datasetName);
LOG.info("Auto-creating destination dataset: %s", sanitizedDatasetName);
DatasetInfo.Builder datasetInfoBuilder =
DatasetInfo.newBuilder(datasetName)
.setDefaultTableLifetime(this.querySettings.getDestinationDatasetExpirationTime());
String location = this.connection.getLocation();
if (location != null && !location.isEmpty()) {
datasetInfoBuilder.setLocation(location);
}

try {
this.bigQuery.create(datasetInfoBuilder.build());
} catch (BigQueryException ex) {
if (ex.getCode() == HttpURLConnection.HTTP_CONFLICT
|| "duplicate".equalsIgnoreCase(ex.getReason())) {
LOG.fine(
"Destination dataset %s already exists (concurrent creation race).",
sanitizedDatasetName);
return;
}
bigQuery.create(datasetInfoBuilder.build());
throw new BigQueryJdbcException("Failed to create destination dataset: " + datasetName, ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,18 @@ public void setDestinationDatasetExpirationTime(long destinationDatasetExpiratio
validateNonNegative(
destinationDatasetExpirationTime,
BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME);
if (destinationDatasetExpirationTime > 0
&& destinationDatasetExpirationTime
< BigQueryJdbcUrlUtility.MIN_DESTINATION_DATASET_EXPIRATION_TIME_VALUE) {
LOG.warning(
"Clamping %s from %d ms to BigQuery minimum %d ms.",
BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME,
destinationDatasetExpirationTime,
BigQueryJdbcUrlUtility.MIN_DESTINATION_DATASET_EXPIRATION_TIME_VALUE);
this.destinationDatasetExpirationTime =
BigQueryJdbcUrlUtility.MIN_DESTINATION_DATASET_EXPIRATION_TIME_VALUE;
return;
}
this.destinationDatasetExpirationTime = destinationDatasetExpirationTime;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -2217,4 +2218,117 @@ public void testLargeResultTable_withoutLargeResultDatasetUnderStandardSqlThrows
verify(bigquery, never()).create(any(JobInfo.class));
verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any());
}

private static Stream<Arguments> autoCreatedDatasetCases() {
return Stream.of(
Arguments.of(
BigQueryJdbcBaseTest.getUriOAuthServiceAccount()
.append("ProjectId", PROJECT)
.append("Location", "EU")
.append("LargeResultDataset", "auto_eu_dataset")
.toString(),
"auto_eu_dataset",
"EU",
DEFAULT_DATASET_EXPIRATION_MS),
Arguments.of(
BigQueryJdbcBaseTest.getUriOAuthServiceAccount()
.append("ProjectId", PROJECT)
.append("LargeResultDataset", "auto_clamped_dataset")
.append("LargeResultsDatasetExpirationTime", "600000")
.toString(),
"auto_clamped_dataset",
null,
DEFAULT_DATASET_EXPIRATION_MS),
Arguments.of(
BigQueryJdbcBaseTest.getUriOAuthServiceAccount()
.append("ProjectId", PROJECT)
.append("LargeResultDataset", "auto_long_ttl_dataset")
.append("LargeResultsDatasetExpirationTime", "7200000")
.toString(),
"auto_long_ttl_dataset",
null,
7_200_000L),
Arguments.of(
BigQueryJdbcBaseTest.getUriOAuthServiceAccount()
.append("ProjectId", PROJECT)
.append("QueryDialect", "BIG_QUERY")
.append("AllowLargeResults", 1)
.append("LargeResultTable", "explicit_legacy_table")
.toString(),
"_google_jdbc",
null,
DEFAULT_DATASET_EXPIRATION_MS));
}

@ParameterizedTest
@MethodSource("autoCreatedDatasetCases")
public void testAutoCreatedDataset_clampsSubHourTtlAndPreservesValidTtlAndLocation(
String url,
String expectedDatasetName,
String expectedLocation,
long expectedDatasetDefaultLifetimeMs)
throws Exception {
doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(expectedDatasetName)));
setupMockLargeResultJobQuery(StatementType.SELECT, null);

try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1")) {
assertNotNull(rs);
}

ArgumentCaptor<DatasetInfo> datasetCaptor = ArgumentCaptor.forClass(DatasetInfo.class);
verify(bigquery).create(datasetCaptor.capture());
DatasetInfo createdDataset = datasetCaptor.getValue();
assertEquals(expectedDatasetName, createdDataset.getDatasetId().getDataset());
assertEquals(expectedLocation, createdDataset.getLocation());
assertEquals(expectedDatasetDefaultLifetimeMs, createdDataset.getDefaultTableLifetime());
assertNull(createdDataset.getAcl());
}

@Test
public void testAutoCreatedDataset_conflictRaceProceedsAndWrapsOtherDatasetErrors()
throws Exception {
String datasetName = "conflict_dataset";
String url =
BigQueryJdbcBaseTest.getUriOAuthServiceAccount()
.append("ProjectId", PROJECT)
.append("LargeResultDataset", datasetName)
.toString();
setupMockLargeResultJobQuery(StatementType.SELECT, null);

// 1. 409 Conflict on create -> dataset was created concurrently, so proceed with query.
doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName)));
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)).queryWithTimeout(any(QueryJobConfiguration.class), any(), any());

// 2. Non-409 BigQueryException on dataset create -> wrapped as BigQueryJdbcException.
Mockito.reset(bigquery);
doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName)));
doThrow(new BigQueryException(403, "Dataset create denied"))
.when(bigquery)
.create(any(DatasetInfo.class));
try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url);
Statement stmt = conn.createStatement()) {
assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1"));
}

// 3. BigQueryException on initial getDataset -> wrapped as BigQueryJdbcException.
Mockito.reset(bigquery);
doThrow(new BigQueryException(403, "Dataset get denied"))
.when(bigquery)
.getDataset(eq(DatasetId.of(datasetName)));
try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url);
Statement stmt = conn.createStatement()) {
assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,30 @@ public void testDestinationDatasetExpirationTimeAllowsZeroForCompatibility() {
DataSource parsed = DataSource.fromUrl(zeroUrl);
assertEquals(0L, parsed.getDestinationDatasetExpirationTime());
}

@ParameterizedTest
@ValueSource(longs = {1L, 600_000L, 3_599_999L})
public void testDestinationDatasetExpirationTimeClampsSubHourPositiveValuesToMinimum(
long subHourValue) {
long expectedMin = BigQueryJdbcUrlUtility.MIN_DESTINATION_DATASET_EXPIRATION_TIME_VALUE;
DataSource ds = new DataSource();
ds.setDestinationDatasetExpirationTime(subHourValue);
assertEquals(expectedMin, ds.getDestinationDatasetExpirationTime());

String url = baseUrl().append("LargeResultsDatasetExpirationTime", subHourValue).toString();
DataSource parsed = DataSource.fromUrl(url);
assertEquals(expectedMin, parsed.getDestinationDatasetExpirationTime());
}

@ParameterizedTest
@ValueSource(longs = {3_600_000L, 7_200_000L})
public void testDestinationDatasetExpirationTimePreservesAtLeastMinimumValues(long validValue) {
DataSource ds = new DataSource();
ds.setDestinationDatasetExpirationTime(validValue);
assertEquals(validValue, ds.getDestinationDatasetExpirationTime());

String url = baseUrl().append("LargeResultsDatasetExpirationTime", validValue).toString();
DataSource parsed = DataSource.fromUrl(url);
assertEquals(validValue, parsed.getDestinationDatasetExpirationTime());
}
}
Loading