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 @@ -197,7 +197,7 @@ 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. 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`. |
| `LargeResultTable` | `null` | Destination table name for query result sets. When specified, results are written with `WRITE_TRUNCATE` and the table is preserved after close. When omitted while `LargeResultDataset` is set, the driver generates a unique temporary table (`temp_table_<uuid>`) with `WRITE_EMPTY` and asynchronously deletes it (best effort) when its `ResultSet` is closed, replaced on re-execution, or its `Statement`/`Connection` is closed. |
| `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 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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.StandardSQLTypeName;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.exception.BigQueryConversionException;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature;
Expand Down Expand Up @@ -55,6 +56,7 @@
import java.time.ZoneId;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;

Expand All @@ -78,6 +80,7 @@ public abstract class BigQueryBaseResultSet extends BigQueryNoOpsResultSet
private Job job;
private SQLWarning warnings;
private boolean warningsLoaded = false;
private final AtomicReference<TableId> generatedTempTableId = new AtomicReference<>();

protected final SpanContext originalSpanContext;

Expand Down Expand Up @@ -154,6 +157,14 @@ public String getQueryId() {
return queryId;
}

void attachGeneratedTempTable(TableId tableId) {
this.generatedTempTableId.set(tableId);
}

TableId claimGeneratedTempTable() {
return this.generatedTempTableId.getAndSet(null);
}

@Override
public void close() {
if (this.statement != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
String destinationTable;
String destinationDataset;
long destinationDatasetExpirationTime;
private final LargeResultDestinations largeResultDestinations = new LargeResultDestinations();
private final LargeResultDestinations largeResultDestinations;
String kmsKeyName;
String universeDomain;
Map<String, String> authProperties;
Expand Down Expand Up @@ -311,10 +311,17 @@ static String maskPropertyValue(String key, Object value) {
}

BigQueryConnection(String url) throws SQLException {
this(url, DataSource.fromUrl(url));
this(url, DataSource.fromUrl(url), LargeResultDestinations.CLEANUP_EXECUTOR);
}

BigQueryConnection(String url, DataSource ds) throws SQLException {
this(url, ds, LargeResultDestinations.CLEANUP_EXECUTOR);
}

@VisibleForTesting
BigQueryConnection(String url, DataSource ds, Executor tempTableCleanupExecutor)
throws SQLException {
this.largeResultDestinations = new LargeResultDestinations(tempTableCleanupExecutor);
this.connectionId = UUID.randomUUID().toString();
Baggage baggage =
Baggage.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ private ResultSet executeQueryImpl(String sql) throws SQLException {

checkNotClosedOrCanceled();
if (!isSingularResultSet()) {
closeCurrentResultSet(/* honorCloseOnCompletion= */ false);
throw new BigQueryJdbcException(
"Query returned more than one or didn't return any ResultSet.");
}
Expand Down Expand Up @@ -663,6 +664,13 @@ void onResultSetClosed(ResultSet closedResultSet) {
}

private void onResultSetClosedInternal(ResultSet closedResultSet) {
if (closedResultSet instanceof BigQueryBaseResultSet) {
TableId tempTableId = ((BigQueryBaseResultSet) closedResultSet).claimGeneratedTempTable();
if (tempTableId != null) {
this.largeResultDestinations.deleteTempTableAsync(
this.bigQuery, this.connectionId, tempTableId, false, 0L);
}
}
boolean willCloseStatement =
closedResultSet == this.currentResultSet
&& !this.isClosed
Expand Down Expand Up @@ -882,6 +890,10 @@ private void runQuery(

TableId executionTempTableId = tempTablePlan.tempTableId;
boolean applyTempTableExpiration = tempTablePlan.needsTableExpiration;
boolean tempTableExpirationApplied = false;
boolean tempTableHandedToResultSet = false;
boolean jobSucceeded = false;
boolean terminalJobError = false;
boolean executionStarted = false;
BigQueryConnection conn = null;

Expand All @@ -901,12 +913,14 @@ private void runQuery(
resetStatementFields();
}
ExecuteResult executeResult = executeJob(jobConfiguration, conn);
jobSucceeded = true;
checkNotClosedOrCanceled();
if (executionTempTableId != null && applyTempTableExpiration) {
this.largeResultDestinations.applyTempTableExpirationBestEffort(
this.bigQuery,
executionTempTableId,
this.querySettings.getDestinationDatasetExpirationTime());
tempTableExpirationApplied = true;
checkNotClosedOrCanceled();
}
StatementType statementType = getStatementType(executeResult);
Expand All @@ -920,6 +934,13 @@ private void runQuery(
boolean aborted;
synchronized (cancelLock) {
aborted = this.isClosed || this.isCanceled;
if (!aborted
&& executionTempTableId != null
&& this.currentResultSet instanceof BigQueryBaseResultSet) {
((BigQueryBaseResultSet) this.currentResultSet)
.attachGeneratedTempTable(executionTempTableId);
tempTableHandedToResultSet = true;
}
}
if (aborted) {
closeCurrentResultSet(/* honorCloseOnCompletion= */ false);
Expand All @@ -935,6 +956,9 @@ private void runQuery(
throw new BigQueryJdbcException("Interrupted during runQuery", ex);
} catch (BigQueryException ex) {
errorCode = TelemetryManager.extractErrorCode(ex);
if (!jobSucceeded && !this.isCanceled && isTerminalJobError(ex)) {
terminalJobError = true;
}
if (isSyntaxError(ex)) {
throw new BigQueryJdbcSqlSyntaxErrorException("BigQueryException during runQuery", ex);
}
Expand All @@ -943,6 +967,17 @@ private void runQuery(
errorCode = TelemetryManager.extractErrorCode(ex);
throw ex;
} finally {
if (executionStarted
&& executionTempTableId != null
&& !tempTableHandedToResultSet
&& !terminalJobError) {
this.largeResultDestinations.deleteTempTableAsync(
this.bigQuery,
this.connectionId,
executionTempTableId,
applyTempTableExpiration && !tempTableExpirationApplied,
this.querySettings.getDestinationDatasetExpirationTime());
}
long durationMs = System.currentTimeMillis() - startTime;

if (executionStarted) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
* Coordinates destination dataset provisioning and lifecycle management for {@code
Expand All @@ -45,6 +51,36 @@ final class LargeResultDestinations {
new BigQueryJdbcCustomLogger(LargeResultDestinations.class.getName());

static final long MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS = 3_600_000L;
private static final int MAX_CLEANUP_THREADS = 4;
private static final int MAX_PENDING_CLEANUPS = 1024;
private static final long CLEANUP_KEEP_ALIVE_SECONDS = 60L;

static final ExecutorService CLEANUP_EXECUTOR = createCleanupExecutor();

private static ExecutorService createCleanupExecutor() {
AtomicInteger threadCounter = new AtomicInteger(1);
ThreadPoolExecutor executor =
new ThreadPoolExecutor(
MAX_CLEANUP_THREADS,
MAX_CLEANUP_THREADS,
CLEANUP_KEEP_ALIVE_SECONDS,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(MAX_PENDING_CLEANUPS),
runnable -> {
Thread thread =
new Thread(
runnable, "bq-jdbc-temp-table-cleanup-" + threadCounter.getAndIncrement());
thread.setDaemon(true);
return thread;
},
(runnable, pool) ->
LOG.warning(
"Temporary destination table cleanup queue is full (%d pending); relying on"
+ " table expiration.",
MAX_PENDING_CLEANUPS));
executor.allowCoreThreadTimeOut(true);
return executor;
}

// BigQuery's default special-group ACLs added automatically on datasets.insert when no explicit
// ACL list is supplied.
Expand Down Expand Up @@ -73,16 +109,99 @@ static final class TempTablePlan {
}
}

private final Executor cleanupExecutor;
private final AtomicBoolean tempTableUpdateForbidden = new AtomicBoolean(false);
private final AtomicBoolean tempTableDeleteForbidden = new AtomicBoolean(false);

LargeResultDestinations() {
this(CLEANUP_EXECUTOR);
}

LargeResultDestinations(Executor cleanupExecutor) {
this.cleanupExecutor = cleanupExecutor;
}

void resetForReuse() {
this.tempTableUpdateForbidden.set(false);
this.tempTableDeleteForbidden.set(false);
}

boolean isTempTableUpdateForbidden() {
return this.tempTableUpdateForbidden.get();
}

boolean isTempTableDeleteForbidden() {
return this.tempTableDeleteForbidden.get();
}

void deleteTempTableAsync(
BigQuery bigQuery,
String connectionId,
TableId tableId,
boolean applyExpirationFallbackOnFailure,
long expirationTtlMs) {
if (bigQuery == null || tableId == null) {
return;
}
if (this.tempTableDeleteForbidden.get()
&& (!applyExpirationFallbackOnFailure || this.tempTableUpdateForbidden.get())) {
return;
}
this.cleanupExecutor.execute(
() ->
runTempTableCleanup(
bigQuery,
connectionId,
tableId,
applyExpirationFallbackOnFailure,
expirationTtlMs));
}

private void runTempTableCleanup(
BigQuery bigQuery,
String connectionId,
TableId tableId,
boolean applyExpirationFallbackOnFailure,
long expirationTtlMs) {
if (connectionId != null) {
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
deleteTempTableOnce(bigQuery, tableId, applyExpirationFallbackOnFailure, expirationTtlMs);
}
return;
}
deleteTempTableOnce(bigQuery, tableId, applyExpirationFallbackOnFailure, expirationTtlMs);
}

private void deleteTempTableOnce(
BigQuery bigQuery,
TableId tableId,
boolean applyExpirationFallbackOnFailure,
long expirationTtlMs) {
boolean deleted = false;
if (!this.tempTableDeleteForbidden.get()) {
try {
bigQuery.delete(tableId);
LOG.fine("Deleted temporary destination table %s.", tableId);
deleted = true;
} catch (RuntimeException ex) {
if (isAccessDeniedException(ex)) {
if (this.tempTableDeleteForbidden.compareAndSet(false, true)) {
LOG.warning(
"Permission denied deleting temporary destination table %s; skipping further temp"
+ " table deletions on this connection: %s",
tableId, ex.getMessage());
}
} else {
LOG.warning(
"Failed to delete temporary destination table %s: %s", tableId, ex.getMessage());
}
}
}
if (!deleted && applyExpirationFallbackOnFailure) {
applyTempTableExpirationBestEffort(bigQuery, tableId, expirationTtlMs);
}
}

static boolean needsPerTableExpiration(Dataset dataset) {
if (dataset == null) {
return true;
Expand Down
Loading
Loading