Skip to content

[WIP] fix(bigquery-jdbc): migrate BulkInsertWriter from JsonStreamWriter to ProtoSchema StreamWriter - #15184

Open
Neenu1995 wants to merge 1 commit into
fix/swa-v2-1-type-registry-proto-codecsfrom
fix/swa-v2-2-proto-stream-writer
Open

Neenu1995 wants to merge 1 commit into
fix/swa-v2-1-type-registry-proto-codecsfrom
fix/swa-v2-2-proto-stream-writer

Conversation

@Neenu1995

Copy link
Copy Markdown
Contributor

Stack: PR 2 of 6 (base: fix/swa-v2-1-type-registry-proto-codecs)
Bug: b/587340667

Summary

Migrate BigQueryJdbcBulkInsertWriter, BigQueryParameterHandler, and BigQueryPreparedStatement from JsonStreamWriter + createJsonRow to StreamWriter + ProtoSchema, delegating row encoding and parameter compatibility gating to BigQueryTypeRegistry.

Design Decisions

  • Direct StreamWriter + ProtoSchema Over JsonStreamWriter (b/587340667): JsonStreamWriter serializes Gson JsonArrays to UTF-16 strings, reparses them via org.json.JSONArray, and reparses strings into DynamicMessage (ProtoRows) — rejecting Base64 BYTES (requiring ~2M boxed integer objects per 1 MB byte[]) and exposing locale/quoting bugs. Building DynamicMessage (ProtoRows) directly eliminates triple serialization, heap amplification, and transitive org.json coupling without losing schema refresh (which JsonStreamWriter already disables when an explicit TableSchema is supplied).
  • Locale.ROOT Schema Field Normalization: Normalize TableSchema field names with Locale.ROOT before BQTableSchemaToProtoDescriptor because java-bigquerystorage calls default-locale String.toLowerCase() (turning 'I' into 'ı' under tr/az locales).
  • Automatic SQL DML Fallback on Incompatible Columns or Values: Deduplicate BigQueryParameterHandler temporal formatters onto BigQueryTypeRegistry and gate useWriteAPI() via isSupportedWriteApiField and areBatchParametersCompatibleWithWriteApi so ARRAY/STRUCT/RANGE columns, REQUIRED nulls, non-finite floats, or out-of-bounds decimals/dates fall back transparently to SQL DML.

… ProtoSchema StreamWriter

Stack: PR 2 of 6 (base: `fix/swa-v2-1-type-registry-proto-codecs`)

### Summary
- Migrate `BigQueryJdbcBulkInsertWriter` from `JsonStreamWriter` to `StreamWriter` + `ProtoSchema` (`BQTableSchemaToProtoDescriptor` with `Locale.ROOT`-normalized field names + `ProtoSchemaConverter`), removing `createJsonRow` and all `Gson` / `org.json` row objects (`b/587340667`).
- Deduplicate `BigQueryParameterHandler` temporal formatters and `Instant` extraction onto `BigQueryTypeRegistry`, and add `areBatchParametersCompatibleWithWriteApi`.
- Update `BigQueryPreparedStatement` (`bulkInsertWithWriteAPI`, `captureInsertMetadata`, and `useWriteAPI`) to delegate column/parameter Write API gating and `ProtoRows` serialization to `BigQueryTypeRegistry` and `BigQueryParameterHandler`, falling back automatically to standard SQL DML on unsupported columns (`ARRAY`, `STRUCT`, `RANGE`) or out-of-bounds parameter values.

### Why `ProtoSchema` Instead of `JsonStreamWriter`
- **No JSON wire format exists on Storage Write API:** `JsonStreamWriter` converts every `Gson` `JsonArray` to a UTF-16 `String`, reparses it into `org.json.JSONArray`, and reparses strings into `DynamicMessage` (`ProtoRows`) before calling `StreamWriter.append(ProtoRows, offset)`. Encoding `DynamicMessage` directly eliminates triple serialization and avoids coupling to transitive `org.json`.
- **Eliminates `BYTES` heap/GC amplification:** `JsonToProtoMessage` rejects Base64 strings and requires a JSON array of byte integers (~2M boxed objects for 1 MB `byte[]`), whereas `ProtoSchema` copies `byte[]` directly into `ByteString`.
- **Eliminates locale/quoting bugs (`b/587340667`):** Typed JDBC values encode directly into binary Protobuf fields via `BigQueryTypeRegistry` instead of round-tripping through locale- or format-sensitive JSON strings.
- **No loss of schema-refresh behavior:** `JsonStreamWriter`'s automatic schema refresh is already disabled whenever an explicit `TableSchema` is supplied, and `BigQueryJdbcBulkInsertWriter` opens a fresh `PENDING` stream per `executeBatch()`.

### Testing
- `make lint`, `mvn -B -ntp dependency:analyze -Pquick-build -DfailOnWarning=true -Dmdep.analyze.skip=false`, `mvn -q -Denforcer.skip=true -Dclirr.skip=true test-compile`, and `make unittest` (`BigQueryJdbcBulkInsertWriterTest`, `BigQueryParameterHandlerTest`, `BigQueryPreparedStatementSettersTest`, and `BigQueryPreparedStatementWriteApiTest`).
@Neenu1995
Neenu1995 requested review from a team as code owners November 24, 2026 01:42

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request refactors the BigQuery JDBC driver's bulk insert mechanism to use the Storage Write API with ProtoRows and StreamWriter instead of JsonStreamWriter and JSON-based serialization. It introduces field name normalization using Locale.ROOT to prevent locale-specific issues and adds compatibility checks to fall back to SQL batch inserts when columns or values are incompatible with the Write API. The review feedback highlights a compilation error in BigQueryJdbcBulkInsertWriter.initialize due to unhandled checked exceptions, and warns against modifying the JVM-wide default locale in tests, which is redundant and can cause flakiness.

Comment on lines +70 to +80
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);

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.

Comment on lines +75 to +87
Locale saved = Locale.getDefault();
BigQueryWriteClient mockClient = stubWriteClient(-1L);
BigQueryJdbcBulkInsertWriter writer = new BigQueryJdbcBulkInsertWriter();
writer.initialize(tableName, mockClient, null);

assertNotNull(writer.getStreamName());
verify(mockClient).getSettings();
try {
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
writer.initialize(TABLE_NAME, mockClient, null);
assertEquals(STREAM_NAME, writer.getStreamName());
assertNotNull(writer.getDescriptor());
assertNotNull(writer.getDescriptor().findFieldByName("id"));
verify(mockClient).getSettings();
} finally {
Locale.setDefault(saved);
}

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

Modifying the JVM-wide default locale using Locale.setDefault can cause flakiness and race conditions in parallel test execution environments. Since normalizeFieldName explicitly uses Locale.ROOT to normalize field names, its behavior is completely independent of the JVM's default locale. Therefore, setting the default locale to Turkish in this test is redundant and can be safely removed.

    BigQueryWriteClient mockClient = stubWriteClient(-1L);
    BigQueryJdbcBulkInsertWriter writer = new BigQueryJdbcBulkInsertWriter();
    writer.initialize(TABLE_NAME, mockClient, null);
    assertEquals(STREAM_NAME, writer.getStreamName());
    assertNotNull(writer.getDescriptor());
    assertNotNull(writer.getDescriptor().findFieldByName("id"));
    verify(mockClient).getSettings();

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant