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
2 changes: 1 addition & 1 deletion java-bigquery-jdbc/docs/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<uuid>`) 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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");

Expand All @@ -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;

Expand All @@ -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(
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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<Acl> nonDefaultGroupAcls;
private final boolean hasDefaultSpecialGroupAcl;
Expand All @@ -72,7 +151,7 @@ private DatasetAclInspection(
}
}

Dataset ensureDatasetExists(
boolean ensureDatasetAndCheckNeedsTableExpiration(
BigQuery bigQuery,
BigQueryConnection conn,
String datasetName,
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -198,7 +280,7 @@ private static DatasetAclInspection inspectDatasetAcl(List<Acl> 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(
Expand All @@ -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(
Expand Down
Loading
Loading