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 @@ -21,30 +21,38 @@
import com.google.api.core.ApiFutures;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.bigquery.storage.v1.AppendRowsResponse;
import com.google.cloud.bigquery.storage.v1.BQTableSchemaToProtoDescriptor;
import com.google.cloud.bigquery.storage.v1.BigQueryWriteClient;
import com.google.cloud.bigquery.storage.v1.CreateWriteStreamRequest;
import com.google.cloud.bigquery.storage.v1.Exceptions;
import com.google.cloud.bigquery.storage.v1.Exceptions.StorageException;
import com.google.cloud.bigquery.storage.v1.FinalizeWriteStreamResponse;
import com.google.cloud.bigquery.storage.v1.JsonStreamWriter;
import com.google.cloud.bigquery.storage.v1.ProtoRows;
import com.google.cloud.bigquery.storage.v1.ProtoSchema;
import com.google.cloud.bigquery.storage.v1.ProtoSchemaConverter;
import com.google.cloud.bigquery.storage.v1.StreamWriter;
import com.google.cloud.bigquery.storage.v1.TableFieldSchema;
import com.google.cloud.bigquery.storage.v1.TableName;
import com.google.cloud.bigquery.storage.v1.TableSchema;
import com.google.cloud.bigquery.storage.v1.WriteStream;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.JsonArray;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.Phaser;
import java.util.logging.Level;
import javax.annotation.concurrent.GuardedBy;

class BigQueryJdbcBulkInsertWriter {
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcBulkInsertWriter.class.getName());
private JsonStreamWriter jsonStreamWriter;
private StreamWriter streamWriter;
private volatile Descriptor descriptor;
private final Phaser openRequestCount = new Phaser(1);
private final Object streamLock = new Object();

@GuardedBy("lock")
@GuardedBy("streamLock")
private RuntimeException error = null;

void initialize(TableName parentTable, BigQueryWriteClient client, RetrySettings retrySettings)
Expand All @@ -59,54 +67,85 @@ void initialize(TableName parentTable, BigQueryWriteClient client, RetrySettings
.setWriteStream(stream)
.build();
WriteStream writeStream = client.createWriteStream(createWriteStreamRequest);
this.descriptor =
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
normalizeTableSchemaFieldNames(writeStream.getTableSchema()));
ProtoSchema protoSchema = ProtoSchemaConverter.convert(this.descriptor);

JsonStreamWriter.Builder jsonStreamWriterBuilder =
JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema(), client);

StreamWriter.Builder streamWriterBuilder =
StreamWriter.newBuilder(writeStream.getName(), client).setWriterSchema(protoSchema);
if (retrySettings != null) {
jsonStreamWriterBuilder.setRetrySettings(retrySettings);
streamWriterBuilder.setRetrySettings(retrySettings);
}
this.streamWriter = buildStreamWriter(streamWriterBuilder);
Comment on lines +70 to +80

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.

high

The initialize method does not declare throws DescriptorValidationException, IOException in its signature, but it calls BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor and buildStreamWriter, both of which throw checked exceptions. This will cause a compilation error. Wrapping these calls in a try-catch block and throwing a RuntimeException (preserving the original cause) resolves this compilation issue.

Suggested change
this.descriptor =
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
normalizeTableSchemaFieldNames(writeStream.getTableSchema()));
ProtoSchema protoSchema = ProtoSchemaConverter.convert(this.descriptor);
JsonStreamWriter.Builder jsonStreamWriterBuilder =
JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema(), client);
StreamWriter.Builder streamWriterBuilder =
StreamWriter.newBuilder(writeStream.getName(), client).setWriterSchema(protoSchema);
if (retrySettings != null) {
jsonStreamWriterBuilder.setRetrySettings(retrySettings);
streamWriterBuilder.setRetrySettings(retrySettings);
}
this.streamWriter = buildStreamWriter(streamWriterBuilder);
try {
this.descriptor =
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
normalizeTableSchemaFieldNames(writeStream.getTableSchema()));
ProtoSchema protoSchema = ProtoSchemaConverter.convert(this.descriptor);
StreamWriter.Builder streamWriterBuilder =
StreamWriter.newBuilder(writeStream.getName(), client).setWriterSchema(protoSchema);
if (retrySettings != null) {
streamWriterBuilder.setRetrySettings(retrySettings);
}
this.streamWriter = buildStreamWriter(streamWriterBuilder);
} catch (DescriptorValidationException | IOException e) {
throw new RuntimeException("Failed to initialize StreamWriter", e);
}
References
  1. When catching an exception and throwing a new custom exception, preserve the original exception as the cause to maintain the exception chain and aid in debugging.

}

StreamWriter buildStreamWriter(StreamWriter.Builder builder) throws IOException {
return builder.build();
}

Descriptor getDescriptor() {
return this.descriptor;
}

this.jsonStreamWriter = jsonStreamWriterBuilder.build();
// 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) {
TableSchema.Builder builder = schema.toBuilder().clearFields();
for (TableFieldSchema field : schema.getFieldsList()) {
builder.addFields(normalizeFieldName(field));
}
return builder.build();
}

private static TableFieldSchema normalizeFieldName(TableFieldSchema field) {
TableFieldSchema.Builder builder =
field.toBuilder().setName(field.getName().toLowerCase(Locale.ROOT));
if (field.getFieldsCount() > 0) {
builder.clearFields();
for (TableFieldSchema subField : field.getFieldsList()) {
builder.addFields(normalizeFieldName(subField));
}
}
return builder.build();
}

void append(JsonArray data, long offset) throws DescriptorValidationException, IOException {
void append(ProtoRows rows, long offset) throws IOException {
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Appending %d rows at offset %d", data.size(), offset);
LOG.finer("Appending %d rows at offset %d", rows.getSerializedRowsCount(), offset);
}
synchronized (this.streamLock) {
if (this.error != null) {
throw this.error;
}
}

ApiFuture<AppendRowsResponse> future = jsonStreamWriter.append(data, offset);
ApiFuture<AppendRowsResponse> future = streamWriter.append(rows, offset);
ApiFutures.addCallback(
future, new AppendCompleteCallback(this), MoreExecutors.directExecutor());
openRequestCount.register();
}

long cleanup(BigQueryWriteClient client) {
LOG.finer("++enter++");
LOG.fine("Cleaning up bulk insert writer for stream: %s", jsonStreamWriter.getStreamName());
LOG.fine("Cleaning up bulk insert writer for stream: %s", streamWriter.getStreamName());
openRequestCount.arriveAndAwaitAdvance();
jsonStreamWriter.close();
streamWriter.close();

synchronized (this.streamLock) {
if (this.error != null) {
throw this.error;
}
}

// Finalize the stream.
FinalizeWriteStreamResponse finalizeResponse =
client.finalizeWriteStream(jsonStreamWriter.getStreamName());
LOG.finer("Rows written: " + finalizeResponse.getRowCount());
client.finalizeWriteStream(streamWriter.getStreamName());
LOG.finer("Rows written: %d", finalizeResponse.getRowCount());
return finalizeResponse.getRowCount();
}

String getStreamName() {
return jsonStreamWriter.getStreamName();
return streamWriter.getStreamName();
}

static class AppendCompleteCallback implements ApiFutureCallback<AppendRowsResponse> {
Expand All @@ -117,12 +156,14 @@ static class AppendCompleteCallback implements ApiFutureCallback<AppendRowsRespo
this.parent = parent;
}

@Override
public void onSuccess(AppendRowsResponse response) {
done();
}

@Override
public void onFailure(Throwable throwable) {
parent.LOG.warning(
LOG.warning(
"Append failed for stream %s: %s", parent.getStreamName(), throwable.getMessage());
synchronized (this.parent.streamLock) {
if (this.parent.error == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.bigquery.jdbc;

import com.google.cloud.Tuple;
import com.google.cloud.bigquery.FieldList;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryParameterValue;
import com.google.cloud.bigquery.StandardSQLTypeName;
Expand All @@ -33,38 +34,19 @@
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Queue;

class BigQueryParameterHandler {
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryParameterHandler.class.getName());
private final int parametersArraySize;
private final boolean enableTimestampPicos;
final ArrayList<BigQueryJdbcParameter> parametersList;
// TIMESTAMP is rendered in UTC with a trailing 'Z': the instant is preserved, the output does not
// depend on the JVM zone, and QueryParameterValue's validator accepts 'Z' but rejects "-05:00".
// Locale.ROOT marks these as wire formats; the patterns are numeric-only, so it is a guard, not
// a fix.
private static final DateTimeFormatter TIMESTAMP_MICROS_UTC =
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSXXX", Locale.ROOT);
private static final DateTimeFormatter TIMESTAMP_NANOS_UTC =
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSSSSXXX", Locale.ROOT);
// DATETIME is a zone-less wall clock; the validator requires six fraction digits and no offset.
private static final DateTimeFormatter DATETIME_MICROS =
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS", Locale.ROOT);
private static final DateTimeFormatter DATE_DIGITS =
DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT);
private static final DateTimeFormatter TIME_MICROS =
DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS", Locale.ROOT);

/** Wall-clock digits for DATETIME (read as UTC if sent to TIMESTAMP). Nanos are truncated. */
static String formatDateTimeDigits(LocalDateTime value) {
return DATETIME_MICROS.format(value);
return BigQueryTypeRegistry.DATETIME_MICROS.format(value);
}

/**
Expand All @@ -83,14 +65,9 @@ static Tuple<Object, Class<?>> bindingForJavaTime(Object value) {
if (value instanceof LocalDateTime) {
return Tuple.of(formatDateTimeDigits((LocalDateTime) value), String.class);
}
if (value instanceof OffsetDateTime) {
return Tuple.of(Timestamp.from(((OffsetDateTime) value).toInstant()), Timestamp.class);
}
if (value instanceof ZonedDateTime) {
return Tuple.of(Timestamp.from(((ZonedDateTime) value).toInstant()), Timestamp.class);
}
if (value instanceof Instant) {
return Tuple.of(Timestamp.from((Instant) value), Timestamp.class);
Instant instant = BigQueryTypeRegistry.extractInstant(value);
if (instant != null && !(value instanceof Timestamp)) {
return Tuple.of(Timestamp.from(instant), Timestamp.class);
}
return null;
}
Expand Down Expand Up @@ -166,19 +143,9 @@ static Object formatValueForQueryParameter(
return ((Number) parameterValue).doubleValue();
}
if (sqlType == StandardSQLTypeName.TIMESTAMP) {
// Reduce to an Instant and render in UTC so digits and 'Z' can never disagree.
if (parameterValue instanceof Timestamp) {
return formatInstantUtc(((Timestamp) parameterValue).toInstant(), enableTimestampPicos);
}
if (parameterValue instanceof OffsetDateTime) {
return formatInstantUtc(
((OffsetDateTime) parameterValue).toInstant(), enableTimestampPicos);
}
if (parameterValue instanceof ZonedDateTime) {
return formatInstantUtc(((ZonedDateTime) parameterValue).toInstant(), enableTimestampPicos);
}
if (parameterValue instanceof Instant) {
return formatInstantUtc((Instant) parameterValue, enableTimestampPicos);
Instant instant = BigQueryTypeRegistry.extractInstant(parameterValue);
if (instant != null) {
return formatInstantUtc(instant, enableTimestampPicos);
}
if (parameterValue instanceof String) {
String str = ((String) parameterValue).trim();
Expand All @@ -193,19 +160,20 @@ static Object formatValueForQueryParameter(
// Civil java.time values are sent as their digits. Boxing into java.sql would shift
// 1582-10-05..14 (no such days in its calendar) and drop sub-second TIME digits.
if (parameterValue instanceof LocalDate) {
return DATE_DIGITS.format((LocalDate) parameterValue);
return BigQueryTypeRegistry.DATE_DIGITS.format((LocalDate) parameterValue);
}
if (parameterValue instanceof LocalTime) {
return TIME_MICROS.format((LocalTime) parameterValue);
return BigQueryTypeRegistry.TIME_MICROS.format((LocalTime) parameterValue);
}
if (parameterValue instanceof LocalDateTime) {
return DATETIME_MICROS.format((LocalDateTime) parameterValue);
return BigQueryTypeRegistry.DATETIME_MICROS.format((LocalDateTime) parameterValue);
}

if (parameterValue instanceof Timestamp) {
// DATETIME slot: JVM-local wall-clock digits, six-digit fraction, no offset (prior
// behaviour).
return DATETIME_MICROS.format(((Timestamp) parameterValue).toLocalDateTime());
return BigQueryTypeRegistry.DATETIME_MICROS.format(
((Timestamp) parameterValue).toLocalDateTime());
}

if (parameterValue instanceof Time) {
Expand All @@ -222,10 +190,8 @@ static Object formatValueForQueryParameter(
}

/** Renders an absolute instant as UTC wall-clock digits with a trailing 'Z'. */
private static String formatInstantUtc(Instant instant, boolean enableTimestampPicos) {
// Fixed-width 'S' truncates (does not round), matching the legacy nanos/1000*1000 behaviour.
return (enableTimestampPicos ? TIMESTAMP_NANOS_UTC : TIMESTAMP_MICROS_UTC)
.format(instant.atOffset(ZoneOffset.UTC));
static String formatInstantUtc(Instant instant, boolean enableTimestampPicos) {
return BigQueryTypeRegistry.formatInstantUtc(instant, enableTimestampPicos);
}

private BigQueryJdbcParameter getOrCreateParameter(int parameterIndex) {
Expand Down Expand Up @@ -487,4 +453,19 @@ StandardSQLTypeName getSqlType(String name) {
int getParametersArraySize() {
return this.parametersArraySize;
}

static boolean areBatchParametersCompatibleWithWriteApi(
FieldList fields, Queue<ArrayList<BigQueryJdbcParameter>> batchParameters) {
for (ArrayList<BigQueryJdbcParameter> parameterList : batchParameters) {
if (parameterList == null || parameterList.size() != fields.size()) {
return false;
}
for (int i = 0; i < fields.size(); i++) {
if (!BigQueryTypeRegistry.isCompatibleWithWriteApi(fields.get(i), parameterList.get(i))) {
return false;
}
}
}
return true;
}
}
Loading
Loading