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
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,13 @@ void initialize(TableName parentTable, BigQueryWriteClient client, RetrySettings
.build();
WriteStream writeStream = client.createWriteStream(createWriteStreamRequest);
this.streamName = writeStream.getName();
TableSchema streamSchema = writeStream.getTableSchema();
if (!isSupportedStreamTableSchema(streamSchema)) {
return;
}
this.descriptor =
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
normalizeTableSchemaFieldNames(writeStream.getTableSchema()));
normalizeTableSchemaFieldNames(streamSchema));
ProtoSchema protoSchema = ProtoSchemaConverter.convert(this.descriptor);

StreamWriter.Builder streamWriterBuilder =
Expand All @@ -92,6 +96,24 @@ Descriptor getDescriptor() {
return this.descriptor;
}

private static boolean isSupportedStreamTableSchema(TableSchema schema) {
if (schema == null || schema.getFieldsCount() == 0) {
return false;
}
for (TableFieldSchema field : schema.getFieldsList()) {
TableFieldSchema.Type t = field.getType();
if (field.getMode() == TableFieldSchema.Mode.REPEATED
|| field.getFieldsCount() > 0
|| t == TableFieldSchema.Type.TYPE_UNSPECIFIED
|| t == TableFieldSchema.Type.UNRECOGNIZED
|| t == TableFieldSchema.Type.STRUCT
|| t == TableFieldSchema.Type.RANGE) {
return false;
}
}
return true;
}

// Lowercase field names with Locale.ROOT upfront because BQTableSchemaToProtoDescriptor calls
// String.toLowerCase() with the JVM default locale (turning 'I' into 'ı' under tr/az locales).
private static TableSchema normalizeTableSchemaFieldNames(TableSchema schema) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ static Tuple<Object, Class<?>> bindingForJavaTime(Object value) {
this(parameterCount, new ArrayList<>(parameterCount), enableTimestampPicos);
}

BigQueryParameterHandler(
private BigQueryParameterHandler(
int parameterCount,
ArrayList<BigQueryJdbcParameter> parametersList,
boolean enableTimestampPicos) {
Expand Down Expand Up @@ -115,19 +115,24 @@ QueryJobConfiguration.Builder configureParameters(
i, this.parametersArraySize));
}

Object parameterValue = getParameter(i);
StandardSQLTypeName sqlType = getSqlType(i);
parameterValue =
formatValueForQueryParameter(parameterValue, sqlType, this.enableTimestampPicos);
QueryParameterValue queryParameter =
toQueryParameterValue(this.parametersList.get(arrayIndex), this.enableTimestampPicos);
LOG.finest(
"Parameter %s of type %s at index %s added to QueryJobConfiguration",
parameterValue, sqlType, i);
jobConfigurationBuilder.addPositionalParameter(
QueryParameterValue.of(parameterValue, sqlType));
queryParameter.getValue(), queryParameter.getType(), i);
jobConfigurationBuilder.addPositionalParameter(queryParameter);
}
return jobConfigurationBuilder;
}

static QueryParameterValue toQueryParameterValue(
BigQueryJdbcParameter parameter, boolean enableTimestampPicos) {
StandardSQLTypeName sqlType = parameter.getSqlType();
Object formatted =
formatValueForQueryParameter(parameter.getValue(), sqlType, enableTimestampPicos);
return QueryParameterValue.of(formatted, sqlType);
}

static Object formatValueForQueryParameter(
Object parameterValue, StandardSQLTypeName sqlType, boolean enableTimestampPicos) {
if (parameterValue == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.services.bigquery.model.QueryParameter;
import com.google.cloud.Tuple;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.FieldList;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
Expand All @@ -42,6 +44,7 @@
import com.google.cloud.bigquery.storage.v1.TableName;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.Descriptors.FieldDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
Expand Down Expand Up @@ -84,6 +87,7 @@ class BigQueryPreparedStatement extends BigQueryStatement implements PreparedSta
protected final int parameterCount;
protected final String currentQuery;
private final DirectInsertShape directInsertShape;
private boolean insertMetadataEvaluated = false;
private Queue<ArrayList<BigQueryJdbcParameter>> batchParameters = new LinkedList<>();
// Both hold statistics.getSchema(), which reports different things per statement type: the rows
// a SELECT returns, versus the columns an INSERT writes.
Expand Down Expand Up @@ -124,7 +128,7 @@ private int resolveParameterCount(String query, QueryStatistics queryStatistics)
* of the query text, so a statement stays usable against a service that refuses the dry run.
*/
private QueryStatistics describeQueryQuietly() {
if (this.currentQuery.indexOf(POSITIONAL_PARAMETER_CHAR) == -1) {
if (this.currentQuery.indexOf(POSITIONAL_PARAMETER_CHAR) == -1 || getUseLegacySql()) {
return null;
}
try {
Expand Down Expand Up @@ -172,26 +176,51 @@ private static StandardSQLTypeName toStandardSqlType(String typeName) {
// for the Storage Write API. Statements with SQL expressions, partial column lists, or
// unsupported column types leave insertSchema null so executeBatch uses standard SQL execution.
private void captureInsertMetadata(QueryStatistics statistics) {
if (statistics == null
|| this.directInsertShape == null
if (statistics == null) {
return;
}
this.insertMetadataEvaluated = true;
if (this.directInsertShape == null
|| !QueryStatistics.StatementType.INSERT.equals(statistics.getStatementType())
|| statistics.getSchema() == null
|| statistics.getReferencedTables() == null
|| statistics.getReferencedTables().stream().distinct().count() != 1) {
return;
}
TableId tableId = statistics.getReferencedTables().get(0);
String project = resolveTargetProject(tableId);
if (project == null || tableId.getDataset() == null || tableId.getTable() == null) {
return;
}
Schema resolvedSchema =
resolveInsertSchema(statistics.getSchema(), this.directInsertShape, this.parameterCount);
if (resolvedSchema == null) {
return;
}
this.insertSchema = resolvedSchema;
TableId tableId = statistics.getReferencedTables().get(0);
this.insertTableName =
TableName.of(tableId.getProject(), tableId.getDataset(), tableId.getTable());
this.insertTableName = TableName.of(project, tableId.getDataset(), tableId.getTable());
LOG.finer("insertTableName: %s, insertSchema: %s", this.insertTableName, this.insertSchema);
}

private String resolveTargetProject(TableId tableId) {
if (tableId.getProject() != null) {
return tableId.getProject();
}
DatasetId defaultDataset = this.querySettings.getDefaultDataset();
if (this.directInsertShape != null
&& this.directInsertShape.unqualifiedTable
&& defaultDataset != null
&& defaultDataset.getProject() != null) {
return defaultDataset.getProject();
}
String catalog = this.connection != null ? this.connection.getCatalog() : null;
if (catalog != null) {
return catalog;
}
BigQuery bq = this.connection != null ? this.connection.getBigQuery() : null;
return bq != null && bq.getOptions() != null ? bq.getOptions().getProjectId() : null;
}

static Schema resolveInsertSchema(
Schema tableSchema, DirectInsertShape shape, int parameterCount) {
if (tableSchema == null || shape == null) {
Expand Down Expand Up @@ -800,13 +829,19 @@ public int[] executeBatch() throws SQLException {

private int[] executeBatchInternal(int[] result) throws SQLException {
// The constructor's dry run may have happened before the target table existed.
if (this.insertSchema == null
if (!this.insertMetadataEvaluated
&& this.directInsertShape != null
&& this.querySettings.isUseWriteAPI()
&& !getUseLegacySql()
&& (this.connection == null || !this.connection.isTransactionStarted())
&& this.batchParameters.size() >= this.querySettings.getWriteAPIActivationRowCount()) {
this.insertMetadataEvaluated = true;
try {
captureInsertMetadata(
getQueryStatistics(getWriteBatchJobConfiguration(this.batchParameters.peek())));
QueryStatistics statistics = describePositionalParameterQuery(this.currentQuery);
if (statistics != null) {
applyInferredParameterTypes(statistics);
captureInsertMetadata(statistics);
}
} catch (SQLException | RuntimeException ex) {
LOG.warning(ex, "Could not describe INSERT target; using the standard batch path.");
}
Expand All @@ -815,22 +850,23 @@ private int[] executeBatchInternal(int[] result) throws SQLException {
if (useWriteAPI()) {
long startTime = System.currentTimeMillis();
int fallbackErrorCode = 1000;
boolean recordWriteApiTelemetry = true;
StatementExecution.Builder writeApiExecutionBuilder =
StatementExecution.newBuilder()
.setStatementType(StatementType.STATEMENT_TYPE_INSERT)
.setQueryApiType(QueryApiType.QUERY_API_TYPE_WRITE_API);
try {
// Lifecycle of the cached BigQueryWriteClient belongs to BigQueryConnection.close().
BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient();
LOG.info("Using Write API for bulk INSERT operation.");

long rowCount = bulkInsertWithWriteAPI(writeClient);
int[] insertArray = new int[Math.toIntExact(rowCount)];
Arrays.fill(insertArray, 1);

writeApiExecutionBuilder.setStatus(Status.STATUS_SUCCESS);

return insertArray;
if (rowCount >= 0) {
int[] insertArray = new int[Math.toIntExact(rowCount)];
Arrays.fill(insertArray, 1);
writeApiExecutionBuilder.setStatus(Status.STATUS_SUCCESS);
return insertArray;
}
recordWriteApiTelemetry = false;

} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Expand All @@ -846,15 +882,17 @@ private int[] executeBatchInternal(int[] result) throws SQLException {
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
throw new BigQueryJdbcException("Failed to execute batch with Write API", e);
} finally {
if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) {
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
if (recordWriteApiTelemetry) {
if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) {
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
}
long durationMs = System.currentTimeMillis() - startTime;
TelemetryManager.recordStatementExecution(writeApiExecutionBuilder, durationMs);
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS);
}
long durationMs = System.currentTimeMillis() - startTime;
TelemetryManager.recordStatementExecution(writeApiExecutionBuilder, durationMs);
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS);
}

} else {
}
if (!useWriteAPI()) {
try {
LOG.info("Using individual INSERT query runs.");
int count = this.batchParameters.size();
Expand Down Expand Up @@ -884,6 +922,31 @@ private int[] executeBatchInternal(int[] result) throws SQLException {
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS);
}
}
return result;
}

private boolean isWriteStreamCompatible(BigQueryJdbcBulkInsertWriter writer) {
Descriptor descriptor = writer.getDescriptor();
FieldList insertFields = this.insertSchema.getFields();
if (descriptor == null || descriptor.getFields().size() != insertFields.size()) {
return false;
}
for (int colIdx = 0; colIdx < insertFields.size(); colIdx++) {
FieldDescriptor fd =
descriptor.findFieldByName(
BigQueryTypeRegistry.toProtoFieldName(insertFields.get(colIdx).getName()));
if (fd == null) {
return false;
}
if (fd.isRequired()) {
for (ArrayList<BigQueryJdbcParameter> row : this.batchParameters) {
if (row.get(colIdx).getValue() == null) {
return false;
}
}
}
}
return true;
}

BigQueryJdbcBulkInsertWriter createBulkInsertWriter() {
Expand All @@ -902,6 +965,11 @@ private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient)
long rowCount;
try {
bulkInsertWriter.initialize(this.insertTableName, bigQueryWriteClient, retrySettings);
if (!isWriteStreamCompatible(bulkInsertWriter)) {
this.insertSchema = null;
return -1L;
}
LOG.info("Using Write API for bulk INSERT operation.");
long offset = 0;
ProtoRows.Builder protoRowsBuilder = ProtoRows.newBuilder();
FieldList fieldLists = this.insertSchema.getFields();
Expand Down Expand Up @@ -948,36 +1016,24 @@ private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient)
return rowCount;
}

QueryJobConfiguration getWriteBatchJobConfiguration(
ArrayList<BigQueryJdbcParameter> currentParameterList) throws SQLException {
LOG.finer("++enter++");
BigQueryParameterHandler batchHandler =
new BigQueryParameterHandler(
this.parameterCount, currentParameterList, this.isEnableTimestampPicos());
QueryJobConfiguration.Builder jobConfiguration = getJobConfig(this.currentQuery);
jobConfiguration.setParameterMode("POSITIONAL");
jobConfiguration = batchHandler.configureParameters(jobConfiguration);
return jobConfiguration.build();
}

QueryJobConfiguration getStandardBatchJobConfiguration(String query) throws SQLException {
LOG.finer("++enter++");
QueryJobConfiguration.Builder jobConfiguration = getJobConfig(query);
jobConfiguration.setParameterMode("POSITIONAL");
jobConfiguration.setPriority(QueryJobConfiguration.Priority.BATCH);
boolean enableTimestampPicos = this.isEnableTimestampPicos();
int index = 0;
while (!this.batchParameters.isEmpty()) {
ArrayList<BigQueryJdbcParameter> parameterList = this.batchParameters.poll();

for (BigQueryJdbcParameter parameter : parameterList) {
Object parameterValue =
BigQueryParameterHandler.formatValueForQueryParameter(
parameter.getValue(), parameter.getSqlType(), this.isEnableTimestampPicos());
StandardSQLTypeName sqlType = parameter.getSqlType();
for (int i = 0; i < this.parameterCount; i++) {
BigQueryJdbcParameter parameter = parameterList.get(i);
Comment on lines +1029 to +1030

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using a hardcoded loop up to this.parameterCount can throw an IndexOutOfBoundsException if parameterList is not fully populated (e.g., if some parameters were not set). It is safer to limit the loop to the actual size of the parameter list.

Suggested change
for (int i = 0; i < this.parameterCount; i++) {
BigQueryJdbcParameter parameter = parameterList.get(i);
int paramsToBind = Math.min(this.parameterCount, parameterList.size());
for (int i = 0; i < paramsToBind; i++) {
BigQueryJdbcParameter parameter = parameterList.get(i);

QueryParameterValue queryParameter =
BigQueryParameterHandler.toQueryParameterValue(parameter, enableTimestampPicos);
LOG.finer(
"Parameter %s of type %s at index %s added to QueryJobConfiguration",
parameterValue, sqlType, index++);
jobConfiguration.addPositionalParameter(QueryParameterValue.of(parameterValue, sqlType));
queryParameter.getValue(), queryParameter.getType(), index++);
jobConfiguration.addPositionalParameter(queryParameter);
}
}
return jobConfiguration.build();
Expand All @@ -988,10 +1044,32 @@ Boolean useWriteAPI() {
return this.querySettings.isUseWriteAPI()
&& this.insertSchema != null
&& this.batchParameters.size() >= this.querySettings.getWriteAPIActivationRowCount()
&& isWriteApiAllowedBySessionAndTransaction()
&& BigQueryParameterHandler.areBatchParametersCompatibleWithWriteApi(
this.insertSchema.getFields(), this.batchParameters);
}

private boolean isWriteApiAllowedBySessionAndTransaction() {
if (this.connection == null) {
return true;
}
if (this.connection.isTransactionStarted()) {
return false;
}
if (this.insertTableName != null && this.insertTableName.getDataset().startsWith("_")) {
BigQueryConnection.SessionState snapshot = this.connection.getSessionStateSnapshot();
boolean sessionActive =
this.connection.isSessionEnabled() || (snapshot != null && snapshot.sessionInfo != null);
DatasetId defaultDataset = this.querySettings.getDefaultDataset();
if (sessionActive
&& (defaultDataset == null
|| !this.insertTableName.getDataset().equals(defaultDataset.getDataset()))) {
return false;
}
}
return true;
}

@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length)
throws SQLException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ private BigQuerySettings generateBigQuerySettings() throws SQLException {
BigQuerySettings.Builder querySettings = BigQuerySettings.newBuilder();
DatasetId defaultDataset = this.connection.getDefaultDataset();
if (defaultDataset != null) {
querySettings.setDefaultDataset(this.connection.defaultDataset);
querySettings.setDefaultDataset(defaultDataset);
}
Long maxBytesBilled = this.connection.getMaxBytesBilled();
if (maxBytesBilled > 0) {
Expand Down Expand Up @@ -1634,9 +1634,9 @@ QueryJobConfiguration.Builder getJobConfig(String query) {
return queryConfigBuilder;
}

private boolean getUseLegacySql() {
return QueryDialectType.BIG_QUERY.equals(
QueryDialectType.valueOf(this.querySettings.getQueryDialect()));
boolean getUseLegacySql() {
String dialect = this.querySettings.getQueryDialect();
return dialect != null && QueryDialectType.BIG_QUERY.equals(QueryDialectType.valueOf(dialect));
}

boolean isEnableTimestampPicos() {
Expand Down
Loading
Loading