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_<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 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). |
| `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 @@ -25,7 +25,9 @@
import com.google.api.gax.rpc.HeaderProvider;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.auth.Credentials;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.ExternalAccountCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.RetryOption;
Expand Down Expand Up @@ -217,6 +219,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
String destinationTable;
String destinationDataset;
long destinationDatasetExpirationTime;
private final LargeResultDestinations largeResultDestinations = new LargeResultDestinations();
String kmsKeyName;
String universeDomain;
Map<String, String> authProperties;
Expand Down Expand Up @@ -742,6 +745,10 @@ long getDestinationDatasetExpirationTime() {
return this.destinationDatasetExpirationTime;
}

LargeResultDestinations getLargeResultDestinations() {
return this.largeResultDestinations;
}

String getKmsKeyName() {
return this.kmsKeyName;
}
Expand All @@ -756,6 +763,29 @@ public Map<String, String> getAuthProperties() throws BigQueryJdbcException {
return this.authProperties;
}

/**
* Returns a service-account email suitable for {@code Acl.User} owner assignment when available,
* or {@code null} for credentials without an email (such as user OAuth, raw access tokens, or
* federated {@code principal://} IAM members, which strip default group ACLs post-create).
*/
String resolveOwnerEmail() {
String email = null;
try {
if (this.credentials instanceof ServiceAccountSigner) {
email = ((ServiceAccountSigner) this.credentials).getAccount();
} else if (this.credentials instanceof ExternalAccountCredentials) {
email = ((ExternalAccountCredentials) this.credentials).getServiceAccountEmail();
}
} catch (RuntimeException ex) {
LOG.fine("Could not resolve account email from credentials: %s", ex.getMessage());
}
if (email == null) {
return null;
}
String trimmed = email.trim();
return trimmed.contains("@") ? trimmed : null;
}

long getMaxResults() {
return maxResults;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
import com.google.cloud.bigquery.BigQuery.TableDataListOption;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.ConnectionProperty;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.EncryptionConfiguration;
import com.google.cloud.bigquery.FieldValueList;
import com.google.cloud.bigquery.Job;
Expand Down Expand Up @@ -146,6 +144,7 @@ public class BigQueryStatement extends BigQueryNoOpsStatement {
private final BigQuery bigQuery;

final BigQuerySettings querySettings;
private final LargeResultDestinations largeResultDestinations;

// Variables Required for the ReferenceQueue implementation
static ReferenceQueue<BigQueryArrowResultSet> referenceQueueArrowRs = new ReferenceQueue<>();
Expand Down Expand Up @@ -211,6 +210,10 @@ public BigQueryStatement(BigQueryConnection connection) throws SQLException {
this.recordTelemetry = recordTelemetry;
this.connectionId = connection.getConnectionId();
this.bigQuery = connection.getBigQuery();
this.largeResultDestinations =
connection.getLargeResultDestinations() != null
? connection.getLargeResultDestinations()
: new LargeResultDestinations();
this.querySettings = generateBigQuerySettings();
}

Expand Down Expand Up @@ -1925,18 +1928,13 @@ 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);
}
bigQuery.create(datasetInfoBuilder.build());
}
BigQueryConnection activeConn = requireOpenConnection();
this.largeResultDestinations.ensureDatasetExists(
this.bigQuery,
activeConn,
datasetName,
this.querySettings.getDestinationDatasetExpirationTime(),
this::checkNotClosedOrCanceled);
}

private String getDefaultDestinationTable() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.cloud.bigquery.jdbc;

import com.google.cloud.bigquery.Acl;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.DatasetInfo;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* Coordinates destination dataset provisioning and lifecycle management for {@code
* LargeResultDataset} queries.
*/
final class LargeResultDestinations {

private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(LargeResultDestinations.class.getName());

static final long MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS = 3_600_000L;

// BigQuery's default special-group ACLs added automatically on datasets.insert when no explicit
// ACL list is supplied.
private static final Set<Acl.Entity> DEFAULT_DATASET_SPECIAL_GROUPS =
Collections.unmodifiableSet(
new HashSet<>(
Arrays.asList(
Acl.Group.ofProjectOwners(),
Acl.Group.ofProjectWriters(),
Acl.Group.ofProjectReaders())));

@FunctionalInterface
interface AbortCheck {
void check() throws BigQueryJdbcException;
}

private static final class DatasetAclInspection {
private final List<Acl> nonDefaultGroupAcls;
private final boolean hasDefaultSpecialGroupAcl;
private final boolean hasNonDefaultGroupOwner;

private DatasetAclInspection(
List<Acl> nonDefaultGroupAcls,
boolean hasDefaultSpecialGroupAcl,
boolean hasNonDefaultGroupOwner) {
this.nonDefaultGroupAcls = nonDefaultGroupAcls;
this.hasDefaultSpecialGroupAcl = hasDefaultSpecialGroupAcl;
this.hasNonDefaultGroupOwner = hasNonDefaultGroupOwner;
}
}

Dataset ensureDatasetExists(
BigQuery bigQuery,
BigQueryConnection conn,
String datasetName,
long configuredExpirationMs,
AbortCheck abortCheck)
throws BigQueryJdbcException {
Dataset dataset;
try {
dataset = bigQuery.getDataset(DatasetId.of(datasetName));
} catch (BigQueryException ex) {
throw new BigQueryJdbcException("Failed to check destination dataset: " + datasetName, ex);
}
if (dataset != null) {
return dataset;
}
abortCheck.check();
return createDataset(bigQuery, conn, datasetName, configuredExpirationMs);
}

private Dataset createDataset(
BigQuery bigQuery, BigQueryConnection conn, String datasetName, long configuredExpirationMs)
throws BigQueryJdbcException {
String sanitizedDatasetName = BigQueryConnection.sanitizeForLog(datasetName);
LOG.info("Auto-creating destination dataset: %s", sanitizedDatasetName);
long datasetDefaultTableLifetimeMs =
Math.max(configuredExpirationMs, MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS);
if (configuredExpirationMs < MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS) {
LOG.warning(
"Clamping auto-created dataset %s defaultTableLifetime from %d ms to BigQuery minimum"
+ " %d ms.",
sanitizedDatasetName, configuredExpirationMs, MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS);
}

DatasetInfo.Builder datasetInfoBuilder =
DatasetInfo.newBuilder(datasetName).setDefaultTableLifetime(datasetDefaultTableLifetimeMs);
String location = conn.getLocation();
if (location != null && !location.isEmpty()) {
datasetInfoBuilder.setLocation(location);
}
String ownerEmail = conn.resolveOwnerEmail();
if (ownerEmail != null) {
datasetInfoBuilder.setAcl(
Collections.singletonList(Acl.of(new Acl.User(ownerEmail), Acl.Role.OWNER)));
}

Dataset createdDataset;
try {
createdDataset = bigQuery.create(datasetInfoBuilder.build());
} catch (BigQueryException ex) {
if (isDatasetConflict(ex)) {
return handleDatasetCreationConflict(bigQuery, datasetName, ownerEmail);
}
throw new BigQueryJdbcException("Failed to create destination dataset: " + datasetName, ex);
}

if (ownerEmail != null) {
return createdDataset;
}

try {
return restrictAutoCreatedDatasetAclToCreator(bigQuery, datasetName, createdDataset);
} catch (BigQueryJdbcException ex) {
deleteEmptyDatasetBestEffort(bigQuery, datasetName);
throw ex;
} catch (RuntimeException ex) {
deleteEmptyDatasetBestEffort(bigQuery, datasetName);
throw new BigQueryJdbcException(
"Failed to restrict ACLs on auto-created destination dataset: " + datasetName, ex);
}
}

private Dataset handleDatasetCreationConflict(
BigQuery bigQuery, String datasetName, String ownerEmail) throws BigQueryJdbcException {
LOG.fine(
"Destination dataset %s already exists (concurrent creation race).",
BigQueryConnection.sanitizeForLog(datasetName));
Dataset existingDataset;
try {
existingDataset = bigQuery.getDataset(DatasetId.of(datasetName));
} catch (BigQueryException reloadEx) {
if (ownerEmail == null) {
throw new BigQueryJdbcException(
"Failed to verify ACLs on concurrently created destination dataset: " + datasetName,
reloadEx);
}
LOG.fine(
"Could not reload concurrently created dataset %s: %s",
BigQueryConnection.sanitizeForLog(datasetName), reloadEx.getMessage());
return null;
}
if (ownerEmail == null) {
verifyConcurrentlyCreatedDatasetAclRestricted(datasetName, existingDataset);
}
return existingDataset;
}

private static boolean isDatasetConflict(BigQueryException ex) {
return ex.getCode() == HttpURLConnection.HTTP_CONFLICT
|| "duplicate".equalsIgnoreCase(ex.getReason());
}

private static DatasetAclInspection inspectDatasetAcl(List<Acl> currentAcl) {
List<Acl> nonDefaultGroupAcls = new ArrayList<>();
boolean hasDefaultSpecialGroupAcl = false;
boolean hasNonDefaultGroupOwner = false;
for (Acl acl : currentAcl) {
if (DEFAULT_DATASET_SPECIAL_GROUPS.contains(acl.getEntity())) {
hasDefaultSpecialGroupAcl = true;
} else {
nonDefaultGroupAcls.add(acl);
if (Acl.Role.OWNER.equals(acl.getRole())) {
hasNonDefaultGroupOwner = true;
}
}
}
return new DatasetAclInspection(
nonDefaultGroupAcls, hasDefaultSpecialGroupAcl, hasNonDefaultGroupOwner);
}

/**
* For non-service-account credentials (whose email/principal is not known before {@code
* datasets.insert}), strips BigQuery's default project-wide special-group ACLs via {@code
* 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(
BigQuery bigQuery, String datasetName, Dataset createdDataset) throws BigQueryJdbcException {
if (createdDataset == null || createdDataset.getAcl() == null) {
throw new BigQueryJdbcException(
"Could not verify creator-only ACLs on auto-created destination dataset: " + datasetName);
}
DatasetAclInspection inspection = inspectDatasetAcl(createdDataset.getAcl());
if (!inspection.hasNonDefaultGroupOwner) {
throw new BigQueryJdbcException(
"Auto-created destination dataset does not contain a verifiable creator OWNER ACL: "
+ datasetName);
}
if (!inspection.hasDefaultSpecialGroupAcl) {
return createdDataset;
}
try {
return bigQuery.update(
DatasetInfo.newBuilder(datasetName).setAcl(inspection.nonDefaultGroupAcls).build());
} catch (BigQueryException ex) {
throw new BigQueryJdbcException(
"Failed to restrict ACLs on auto-created destination dataset: " + datasetName, ex);
}
}

/**
* Fails closed on a {@code 409 Conflict} race for non-service-account credentials without
* mutating ACLs on a dataset that may have been created by another actor.
*/
private static void verifyConcurrentlyCreatedDatasetAclRestricted(
String datasetName, Dataset existingDataset) throws BigQueryJdbcException {
if (existingDataset == null || existingDataset.getAcl() == null) {
throw new BigQueryJdbcException(
"Could not verify ACLs on concurrently created destination dataset: "
+ datasetName
+ ". Pre-create LargeResultDataset with the desired ACLs.");
}
DatasetAclInspection inspection = inspectDatasetAcl(existingDataset.getAcl());
if (inspection.hasDefaultSpecialGroupAcl || !inspection.hasNonDefaultGroupOwner) {
throw new BigQueryJdbcException(
"Concurrently created destination dataset does not have verified creator-only ACLs: "
+ datasetName
+ ". Pre-create LargeResultDataset with the desired ACLs.");
}
}

private void deleteEmptyDatasetBestEffort(BigQuery bigQuery, String datasetName) {
try {
bigQuery.delete(DatasetId.of(datasetName));
} catch (RuntimeException ex) {
LOG.warning(
"Failed to clean up empty destination dataset %s after ACL restriction failure: %s",
BigQueryConnection.sanitizeForLog(datasetName), ex.getMessage());
}
}
}
Loading
Loading