Repository navigation
[WIP] fix(bigquery-jdbc): migrate BulkInsertWriter from JsonStreamWriter to ProtoSchema StreamWriter - #15184
Conversation
… 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`).
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
| 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
- 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.
| 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); | ||
| } |
There was a problem hiding this comment.
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();
Stack: PR 2 of 6 (base:
fix/swa-v2-1-type-registry-proto-codecs)Bug: b/587340667
Summary
Migrate
BigQueryJdbcBulkInsertWriter,BigQueryParameterHandler, andBigQueryPreparedStatementfromJsonStreamWriter+createJsonRowtoStreamWriter+ProtoSchema, delegating row encoding and parameter compatibility gating toBigQueryTypeRegistry.Design Decisions
StreamWriter+ProtoSchemaOverJsonStreamWriter(b/587340667):JsonStreamWriterserializesGsonJsonArrays to UTF-16 strings, reparses them viaorg.json.JSONArray, and reparses strings intoDynamicMessage(ProtoRows) — rejecting Base64BYTES(requiring ~2M boxed integer objects per 1 MBbyte[]) and exposing locale/quoting bugs. BuildingDynamicMessage(ProtoRows) directly eliminates triple serialization, heap amplification, and transitiveorg.jsoncoupling without losing schema refresh (whichJsonStreamWriteralready disables when an explicitTableSchemais supplied).Locale.ROOTSchema Field Normalization: NormalizeTableSchemafield names withLocale.ROOTbeforeBQTableSchemaToProtoDescriptorbecausejava-bigquerystoragecalls default-localeString.toLowerCase()(turning'I'into'ı'undertr/azlocales).BigQueryParameterHandlertemporal formatters ontoBigQueryTypeRegistryand gateuseWriteAPI()viaisSupportedWriteApiFieldandareBatchParametersCompatibleWithWriteApisoARRAY/STRUCT/RANGEcolumns,REQUIREDnulls, non-finite floats, or out-of-bounds decimals/dates fall back transparently to SQL DML.