You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by ch...@apache.org on 2023/12/01 18:05:49 UTC
(beam) branch master updated: Support for upgrading BigQuery transforms without upgrading the pipeline (#29550)
This is an automated email from the ASF dual-hosted git repository.
chamikara pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/beam.git
The following commit(s) were added to refs/heads/master by this push:
new 26135b07473 Support for upgrading BigQuery transforms without upgrading the pipeline (#29550)
26135b07473 is described below
commit 26135b074732338c7c1926e21bd394bf5e0ae5c0
Author: Chamikara Jayalath <ch...@gmail.com>
AuthorDate: Fri Dec 1 10:05:42 2023 -0800
Support for upgrading BigQuery transforms without upgrading the pipeline (#29550)
* Support for upgrading BigQuery transforms without upgrading the pipeline
* Fix spotless
* Addressing reviewer comments
* Cleanup
---
.../core/construction/TransformUpgrader.java | 52 +-
.../sdk/expansion/service/ExpansionService.java | 18 +
.../sdk/io/gcp/bigquery/BigQueryIOTranslation.java | 782 +++++++++++++++++++++
.../io/gcp/bigquery/BigQueryIOTranslationTest.java | 303 ++++++++
.../sdk/io/kafka/upgrade/KafkaIOTranslation.java | 26 +-
5 files changed, 1155 insertions(+), 26 deletions(-)
diff --git a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/TransformUpgrader.java b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/TransformUpgrader.java
index 93fe4ddbfaf..e6dce752d06 100644
--- a/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/TransformUpgrader.java
+++ b/runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/TransformUpgrader.java
@@ -17,7 +17,11 @@
*/
package org.apache.beam.runners.core.construction;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collection;
@@ -104,6 +108,15 @@ public class TransformUpgrader implements AutoCloseable {
})
.collect(Collectors.toList());
+ if (!urnsToOverride.isEmpty() && transformsToOverride.isEmpty()) {
+ throw new IllegalArgumentException(
+ "A list of URNs for overriding transforms was provided but the pipeline did not contain "
+ + "any matching transforms. Either make sure to include at least one matching "
+ + "transform in the pipeline or avoid setting the 'transformsToOverride' "
+ + "PipelineOption. Provided list of URNs: "
+ + urnsToOverride);
+ }
+
String serviceAddress;
TransformServiceLauncher service = null;
@@ -232,11 +245,11 @@ public class TransformUpgrader implements AutoCloseable {
expandedTransform.getOutputsMap().values().iterator().next());
} else {
for (Map.Entry<String, String> entry : transformToUpgrade.getOutputsMap().entrySet()) {
- if (expandedTransform.getOutputsMap().keySet().contains(entry.getKey())) {
+ if (!expandedTransform.getOutputsMap().keySet().contains(entry.getKey())) {
throw new IllegalArgumentException(
- "Original transform did not have an output with tag "
+ "Original transform had an output with tag "
+ entry.getKey()
- + " but upgraded transform did.");
+ + " but upgraded transform did not.");
}
String newOutput = expandedTransform.getOutputsMap().get(entry.getKey());
if (newOutput == null) {
@@ -367,4 +380,37 @@ public class TransformUpgrader implements AutoCloseable {
return null;
}
+
+ /**
+ * A utility method that converts an arbitrary serializable object into a byte array.
+ *
+ * @param object an instance of type {@code Serializable}
+ * @return {@code object} converted into a byte array.
+ */
+ public static byte[] toByteArray(Object object) {
+ try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream(bos)) {
+ out.writeObject(object);
+ return bos.toByteArray();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * A utility method that converts a byte array obtained by invoking {@link #toByteArray(Object)}
+ * back to a Java object.
+ *
+ * @param bytes a {@code byte} array generated by invoking the {@link #toByteArray(Object)}
+ * method.
+ * @return re-generated object.
+ */
+ public static Object fromByteArray(byte[] bytes) {
+ try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
+ ObjectInputStream in = new ObjectInputStream(bis)) {
+ return in.readObject();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/sdks/java/expansion-service/src/main/java/org/apache/beam/sdk/expansion/service/ExpansionService.java b/sdks/java/expansion-service/src/main/java/org/apache/beam/sdk/expansion/service/ExpansionService.java
index 8e57ad706fe..ba60fb99d4d 100644
--- a/sdks/java/expansion-service/src/main/java/org/apache/beam/sdk/expansion/service/ExpansionService.java
+++ b/sdks/java/expansion-service/src/main/java/org/apache/beam/sdk/expansion/service/ExpansionService.java
@@ -30,6 +30,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -82,6 +83,7 @@ import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.PDone;
import org.apache.beam.sdk.values.PInput;
import org.apache.beam.sdk.values.POutput;
+import org.apache.beam.sdk.values.PValue;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.vendor.grpc.v1p54p0.com.google.protobuf.ByteString;
@@ -457,6 +459,22 @@ public class ExpansionService extends ExpansionServiceGrpc.ExpansionServiceImplB
i++;
}
return indexToPCollection.build();
+ } else if (output instanceof POutput) {
+ // This is needed to support custom output types.
+ Map<TupleTag<?>, PValue> values = output.expand();
+ Map<String, PCollection<?>> returnMap = new HashMap<>();
+ for (Map.Entry<TupleTag<?>, PValue> entry : values.entrySet()) {
+ if (!(entry.getValue() instanceof PCollection)) {
+ throw new UnsupportedOperationException(
+ "Unable to parse the output type "
+ + output.getClass()
+ + " due to key "
+ + entry.getKey()
+ + " not mapping to a PCollection");
+ }
+ returnMap.put(entry.getKey().getId(), (PCollection<?>) entry.getValue());
+ }
+ return returnMap;
} else {
throw new UnsupportedOperationException("Unknown output type: " + output.getClass());
}
diff --git a/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslation.java b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslation.java
new file mode 100644
index 00000000000..a0c3bdbece5
--- /dev/null
+++ b/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslation.java
@@ -0,0 +1,782 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.sdk.io.gcp.bigquery;
+
+import static org.apache.beam.runners.core.construction.TransformUpgrader.fromByteArray;
+import static org.apache.beam.runners.core.construction.TransformUpgrader.toByteArray;
+
+import com.google.api.services.bigquery.model.Clustering;
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.auto.service.AutoService;
+import com.google.cloud.bigquery.storage.v1.AppendRowsRequest.MissingValueInterpretation;
+import com.google.cloud.bigquery.storage.v1.DataFormat;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.model.pipeline.v1.RunnerApi.FunctionSpec;
+import org.apache.beam.runners.core.construction.PTransformTranslation.TransformPayloadTranslator;
+import org.apache.beam.runners.core.construction.SdkComponents;
+import org.apache.beam.runners.core.construction.TransformPayloadTranslatorRegistrar;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.FromBeamRowFunction;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.QueryPriority;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.ToBeamRowFunction;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.SchemaUpdateOption;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition;
+import org.apache.beam.sdk.io.gcp.bigquery.RowWriterFactory.AvroRowWriterFactory;
+import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
+import org.apache.beam.sdk.runners.AppliedPTransform;
+import org.apache.beam.sdk.schemas.Schema;
+import org.apache.beam.sdk.schemas.Schema.FieldType;
+import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration;
+import org.apache.beam.sdk.transforms.PTransform;
+import org.apache.beam.sdk.transforms.SerializableFunction;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.sdk.values.TypeDescriptor;
+import org.apache.beam.sdk.values.ValueInSingleWindow;
+import org.apache.beam.vendor.grpc.v1p54p0.com.google.protobuf.ByteString;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableMap;
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+@SuppressWarnings({"rawtypes", "nullness"})
+public class BigQueryIOTranslation {
+
+ static class BigQueryIOReadTranslator implements TransformPayloadTranslator<TypedRead<?>> {
+
+ static Schema schema =
+ Schema.builder()
+ .addNullableStringField("json_table_ref")
+ .addNullableStringField("query")
+ .addNullableBooleanField("validate")
+ .addNullableBooleanField("flatten_results")
+ .addNullableBooleanField("use_legacy_sql")
+ .addNullableBooleanField("with_template_compatibility")
+ .addNullableByteArrayField("bigquery_services")
+ .addNullableByteArrayField("parse_fn")
+ .addNullableByteArrayField("datum_reader_factory")
+ .addNullableByteArrayField("query_priority")
+ .addNullableStringField("query_location")
+ .addNullableStringField("query_temp_dataset")
+ .addNullableByteArrayField("method")
+ .addNullableByteArrayField("format")
+ .addNullableArrayField("selected_fields", FieldType.STRING)
+ .addNullableStringField("row_restriction")
+ .addNullableByteArrayField("coder")
+ .addNullableStringField("kms_key")
+ .addNullableByteArrayField("type_descriptor")
+ .addNullableByteArrayField("to_beam_row_fn")
+ .addNullableStringField("from_beam_row_fn")
+ .addNullableBooleanField("use_avro_logical_types")
+ .addNullableBooleanField("projection_pushdown_applied")
+ .build();
+
+ public static final String BIGQUERY_READ_TRANSFORM_URN =
+ "beam:transform:org.apache.beam:bigquery_read:v1";
+
+ @Override
+ public String getUrn() {
+ return BIGQUERY_READ_TRANSFORM_URN;
+ }
+
+ @Override
+ public RunnerApi.@Nullable FunctionSpec translate(
+ AppliedPTransform<?, ?, TypedRead<?>> application, SdkComponents components)
+ throws IOException {
+ // Setting an empty payload since BigQuery transform payload is not actually used by runners
+ // currently.
+ // This can be implemented if runners started actually using the BigQuery transform payload.
+ return FunctionSpec.newBuilder().setUrn(getUrn()).setPayload(ByteString.empty()).build();
+ }
+
+ @Override
+ public Row toConfigRow(TypedRead<?> transform) {
+ Map<String, Object> fieldValues = new HashMap<>();
+
+ if (transform.getJsonTableRef() != null) {
+ fieldValues.put("json_table_ref", transform.getJsonTableRef().get());
+ }
+ if (transform.getQuery() != null) {
+ fieldValues.put("query", transform.getQuery().get());
+ }
+ fieldValues.put("validate", transform.getValidate());
+ fieldValues.put("flatten_results", transform.getFlattenResults());
+ fieldValues.put("use_legacy_sql", transform.getUseLegacySql());
+ fieldValues.put("with_template_compatibility", transform.getWithTemplateCompatibility());
+
+ if (transform.getBigQueryServices() != null) {
+ fieldValues.put("bigquery_services", toByteArray(transform.getBigQueryServices()));
+ }
+ if (transform.getParseFn() != null) {
+ fieldValues.put("parse_fn", toByteArray(transform.getParseFn()));
+ }
+ if (transform.getDatumReaderFactory() != null) {
+ fieldValues.put("datum_reader_factory", toByteArray(transform.getDatumReaderFactory()));
+ }
+ if (transform.getQueryPriority() != null) {
+ fieldValues.put("query_priority", toByteArray(transform.getQueryPriority()));
+ }
+ if (transform.getQueryLocation() != null) {
+ fieldValues.put("query_location", transform.getQueryLocation());
+ }
+ if (transform.getQueryTempDataset() != null) {
+ fieldValues.put("query_temp_dataset", transform.getQueryTempDataset());
+ }
+ if (transform.getMethod() != null) {
+ fieldValues.put("method", toByteArray(transform.getMethod()));
+ }
+ if (transform.getFormat() != null) {
+ fieldValues.put("format", toByteArray(transform.getFormat()));
+ }
+ if (transform.getSelectedFields() != null && !transform.getSelectedFields().get().isEmpty()) {
+ fieldValues.put("selected_fields", transform.getSelectedFields().get());
+ }
+ if (transform.getRowRestriction() != null) {
+ fieldValues.put("row_restriction", transform.getRowRestriction().get());
+ }
+ if (transform.getCoder() != null) {
+ fieldValues.put("coder", toByteArray(transform.getCoder()));
+ }
+ if (transform.getKmsKey() != null) {
+ fieldValues.put("kms_key", transform.getKmsKey());
+ }
+ if (transform.getTypeDescriptor() != null) {
+ fieldValues.put("type_descriptor", toByteArray(transform.getTypeDescriptor()));
+ }
+ if (transform.getToBeamRowFn() != null) {
+ fieldValues.put("to_beam_row_fn", toByteArray(transform.getToBeamRowFn()));
+ }
+ if (transform.getFromBeamRowFn() != null) {
+ fieldValues.put("from_beam_row_fn", toByteArray(transform.getFromBeamRowFn()));
+ }
+ if (transform.getUseAvroLogicalTypes() != null) {
+ fieldValues.put("use_avro_logical_types", transform.getUseAvroLogicalTypes());
+ }
+ fieldValues.put("projection_pushdown_applied", transform.getProjectionPushdownApplied());
+
+ return Row.withSchema(schema).withFieldValues(fieldValues).build();
+ }
+
+ @Override
+ public TypedRead<?> fromConfigRow(Row configRow) {
+ BigQueryIO.TypedRead.Builder builder = new AutoValue_BigQueryIO_TypedRead.Builder<>();
+
+ String jsonTableRef = configRow.getString("json_table_ref");
+ if (jsonTableRef != null) {
+ builder = builder.setJsonTableRef(StaticValueProvider.of(jsonTableRef));
+ }
+ String query = configRow.getString("query");
+ if (query != null) {
+ builder = builder.setQuery(StaticValueProvider.of(query));
+ }
+ Boolean validate = configRow.getBoolean("validate");
+ if (validate != null) {
+ builder = builder.setValidate(validate);
+ }
+ Boolean flattenResults = configRow.getBoolean("flatten_results");
+ if (flattenResults != null) {
+ builder = builder.setFlattenResults(flattenResults);
+ }
+ Boolean useLegacySQL = configRow.getBoolean("use_legacy_sql");
+ if (useLegacySQL != null) {
+ builder = builder.setUseLegacySql(useLegacySQL);
+ }
+ Boolean withTemplateCompatibility = configRow.getBoolean("with_template_compatibility");
+ if (withTemplateCompatibility != null) {
+ builder = builder.setWithTemplateCompatibility(withTemplateCompatibility);
+ }
+ byte[] bigqueryServicesBytes = configRow.getBytes("bigquery_services");
+ if (bigqueryServicesBytes != null) {
+ builder =
+ builder.setBigQueryServices((BigQueryServices) fromByteArray(bigqueryServicesBytes));
+ }
+ byte[] parseFnBytes = configRow.getBytes("parse_fn");
+ if (parseFnBytes != null) {
+ builder = builder.setParseFn((SerializableFunction) fromByteArray(parseFnBytes));
+ }
+ byte[] datumReaderFactoryBytes = configRow.getBytes("datum_reader_factory");
+ if (datumReaderFactoryBytes != null) {
+ builder =
+ builder.setDatumReaderFactory(
+ (SerializableFunction) fromByteArray(datumReaderFactoryBytes));
+ }
+ byte[] queryPriorityBytes = configRow.getBytes("query_priority");
+ if (queryPriorityBytes != null) {
+ builder = builder.setQueryPriority((QueryPriority) fromByteArray(queryPriorityBytes));
+ }
+ String queryLocation = configRow.getString("query_location");
+ if (queryLocation != null) {
+ builder = builder.setQueryLocation(queryLocation);
+ }
+ String queryTempDataset = configRow.getString("query_temp_dataset");
+ if (queryTempDataset != null) {
+ builder = builder.setQueryTempDataset(queryTempDataset);
+ }
+ byte[] methodBytes = configRow.getBytes("method");
+ if (methodBytes != null) {
+ builder = builder.setMethod((TypedRead.Method) fromByteArray(methodBytes));
+ }
+ byte[] formatBytes = configRow.getBytes("format");
+ if (methodBytes != null) {
+ builder = builder.setFormat((DataFormat) fromByteArray(formatBytes));
+ }
+ Collection<String> selectedFields = configRow.getArray("selected_fields");
+ if (selectedFields != null && !selectedFields.isEmpty()) {
+ builder.setSelectedFields(StaticValueProvider.of(ImmutableList.of(selectedFields)));
+ }
+ String rowRestriction = configRow.getString("row_restriction");
+ if (rowRestriction != null) {
+ builder = builder.setRowRestriction(StaticValueProvider.of(rowRestriction));
+ }
+ byte[] coderBytes = configRow.getBytes("coder");
+ if (coderBytes != null) {
+ builder = builder.setCoder((Coder) fromByteArray(coderBytes));
+ }
+ String kmsKey = configRow.getString("kms_key");
+ if (kmsKey != null) {
+ builder = builder.setKmsKey(kmsKey);
+ }
+ byte[] typeDescriptorBytes = configRow.getBytes("type_descriptor");
+ if (typeDescriptorBytes != null) {
+ builder = builder.setTypeDescriptor((TypeDescriptor) fromByteArray(typeDescriptorBytes));
+ }
+ byte[] toBeamRowFnBytes = configRow.getBytes("to_beam_row_fn");
+ if (toBeamRowFnBytes != null) {
+ builder = builder.setToBeamRowFn((ToBeamRowFunction) fromByteArray(toBeamRowFnBytes));
+ }
+ byte[] fromBeamRowFnBytes = configRow.getBytes("from_beam_row_fn");
+ if (fromBeamRowFnBytes != null) {
+ builder = builder.setFromBeamRowFn((FromBeamRowFunction) fromByteArray(fromBeamRowFnBytes));
+ }
+ Boolean useAvroLogicalTypes = configRow.getBoolean("use_avro_logical_types");
+ if (useAvroLogicalTypes != null) {
+ builder = builder.setUseAvroLogicalTypes(useAvroLogicalTypes);
+ }
+ Boolean projectionPushdownApplied = configRow.getBoolean("projection_pushdown_applied");
+ if (projectionPushdownApplied != null) {
+ builder = builder.setProjectionPushdownApplied(projectionPushdownApplied);
+ }
+
+ return builder.build();
+ }
+ }
+
+ @AutoService(TransformPayloadTranslatorRegistrar.class)
+ public static class ReadRegistrar implements TransformPayloadTranslatorRegistrar {
+
+ @Override
+ @SuppressWarnings({
+ "rawtypes",
+ })
+ public Map<? extends Class<? extends PTransform>, ? extends TransformPayloadTranslator>
+ getTransformPayloadTranslators() {
+ return ImmutableMap.<Class<? extends PTransform>, TransformPayloadTranslator>builder()
+ .put(AutoValue_BigQueryIO_TypedRead.class, new BigQueryIOReadTranslator())
+ .build();
+ }
+ }
+
+ static class BigQueryIOWriteTranslator implements TransformPayloadTranslator<Write<?>> {
+
+ static Schema schema =
+ Schema.builder()
+ .addNullableStringField("json_table_ref")
+ .addNullableByteArrayField("table_function")
+ .addNullableByteArrayField("format_function")
+ .addNullableByteArrayField("format_record_on_failure_function")
+ .addNullableByteArrayField("avro_row_writer_factory")
+ .addNullableByteArrayField("avro_schema_factory")
+ .addNullableBooleanField("use_avro_logical_types")
+ .addNullableByteArrayField("dynamic_destinations")
+ .addNullableStringField("json_schema")
+ .addNullableStringField("json_time_partitioning")
+ .addNullableByteArrayField("clustering")
+ .addNullableByteArrayField("create_disposition")
+ .addNullableByteArrayField("write_disposition")
+ .addNullableArrayField("schema_update_options", FieldType.BYTES)
+ .addNullableStringField("table_description")
+ .addNullableBooleanField("validate")
+ .addNullableByteArrayField("bigquery_services")
+ .addNullableInt32Field("max_files_per_bundle")
+ .addNullableInt64Field("max_file_size")
+ .addNullableInt32Field("num_file_shards")
+ .addNullableInt32Field("num_storage_write_api_streams")
+ .addNullableBooleanField("propagate_successful_storage_api_writes")
+ .addNullableInt32Field("max_files_per_partition")
+ .addNullableInt64Field("max_bytes_per_partition")
+ .addNullableLogicalTypeField("triggerring_frequency", new NanosDuration())
+ .addNullableByteArrayField("method")
+ .addNullableStringField("load_job_project_id")
+ .addNullableByteArrayField("failed_insert_retry_policy")
+ .addNullableStringField("custom_gcs_temp_location")
+ .addNullableBooleanField("extended_error_info")
+ .addNullableBooleanField("skip_invalid_rows")
+ .addNullableBooleanField("ignore_unknown_values")
+ .addNullableBooleanField("ignore_insert_ids")
+ .addNullableInt32Field("max_retry_jobs")
+ .addNullableStringField("kms_key")
+ .addNullableArrayField("primary_key", FieldType.STRING)
+ .addNullableByteArrayField("default_missing_value_interpretation")
+ .addNullableBooleanField("optimize_writes")
+ .addNullableBooleanField("use_beam_schema")
+ .addNullableBooleanField("auto_sharding")
+ .addNullableBooleanField("propagate_successful")
+ .addNullableBooleanField("auto_schema_update")
+ .addNullableByteArrayField("write_protos_class")
+ .addNullableBooleanField("direct_write_protos")
+ .addNullableByteArrayField("deterministic_record_id_fn")
+ .addNullableStringField("write_temp_dataset")
+ .addNullableByteArrayField("row_mutation_information_fn")
+ .build();
+
+ public static final String BIGQUERY_WRITE_TRANSFORM_URN =
+ "beam:transform:org.apache.beam:bigquery_write:v1";
+
+ @Override
+ public String getUrn() {
+ return BIGQUERY_WRITE_TRANSFORM_URN;
+ }
+
+ @Override
+ public @Nullable FunctionSpec translate(
+ AppliedPTransform<?, ?, Write<?>> application, SdkComponents components)
+ throws IOException {
+ // Setting an empty payload since BigQuery transform payload is not actually used by runners
+ // currently.
+ // This can be implemented if runners started actually using the Kafka BigQuery payload.
+ return FunctionSpec.newBuilder().setUrn(getUrn()).setPayload(ByteString.empty()).build();
+ }
+
+ @Override
+ public Row toConfigRow(Write<?> transform) {
+
+ Map<String, Object> fieldValues = new HashMap<>();
+
+ if (transform.getJsonTableRef() != null) {
+ fieldValues.put("json_table_ref", transform.getJsonTableRef().get());
+ }
+ if (transform.getTableFunction() != null) {
+ fieldValues.put("table_function", toByteArray(transform.getTableFunction()));
+ }
+ if (transform.getFormatFunction() != null) {
+ fieldValues.put("format_function", toByteArray(transform.getFormatFunction()));
+ }
+ if (transform.getFormatRecordOnFailureFunction() != null) {
+ fieldValues.put(
+ "format_record_on_failure_function",
+ toByteArray(transform.getFormatRecordOnFailureFunction()));
+ }
+ if (transform.getAvroRowWriterFactory() != null) {
+ fieldValues.put(
+ "avro_row_writer_factory", toByteArray(transform.getAvroRowWriterFactory()));
+ }
+ fieldValues.put("use_avro_logical_types", transform.getUseAvroLogicalTypes());
+ if (transform.getDynamicDestinations() != null) {
+ fieldValues.put("dynamic_destinations", toByteArray(transform.getDynamicDestinations()));
+ }
+ if (transform.getSchemaFromView() != null) {
+ // Property 'getSchemaFromView' cannot be used in a portable way across pipelines since it
+ // is bound to PCollections generated for the current pipeline instance.
+ throw new IllegalArgumentException(
+ "BigQueryIO.Write transforms cannot be converted to a "
+ + "portable row based config due to 'withSchemaFromView' property being set. Please "
+ + "retry without setting this property when configuring your transform");
+ }
+ if (transform.getJsonSchema() != null) {
+ fieldValues.put("json_schema", transform.getJsonSchema().get());
+ }
+ if (transform.getJsonTimePartitioning() != null) {
+ fieldValues.put(
+ "json_time_partitioning", toByteArray(transform.getJsonTimePartitioning().get()));
+ }
+ if (transform.getClustering() != null) {
+ fieldValues.put("clustering", toByteArray(transform.getClustering()));
+ }
+ if (transform.getCreateDisposition() != null) {
+ fieldValues.put("create_disposition", toByteArray(transform.getCreateDisposition()));
+ }
+ if (transform.getWriteDisposition() != null) {
+ fieldValues.put("write_disposition", toByteArray(transform.getWriteDisposition()));
+ }
+ if (transform.getSchemaUpdateOptions() != null
+ && !transform.getSchemaUpdateOptions().isEmpty()) {
+ List<byte[]> schemUpdateOptionsData =
+ transform.getSchemaUpdateOptions().stream()
+ .map(option -> toByteArray(option))
+ .collect(Collectors.toList());
+ fieldValues.put("schema_update_options", schemUpdateOptionsData);
+ }
+ if (transform.getTableDescription() != null) {
+ fieldValues.put("table_description", transform.getTableDescription());
+ }
+ fieldValues.put("validate", transform.getValidate());
+ if (transform.getBigQueryServices() != null) {
+ fieldValues.put("bigquery_services", toByteArray(transform.getBigQueryServices()));
+ }
+ if (transform.getMaxFilesPerBundle() != null) {
+ fieldValues.put("max_files_per_bundle", transform.getMaxFilesPerBundle());
+ }
+ if (transform.getMaxFileSize() != null) {
+ fieldValues.put("max_file_size", transform.getMaxFileSize());
+ }
+ fieldValues.put("num_file_shards", transform.getNumFileShards());
+ fieldValues.put("num_storage_write_api_streams", transform.getNumStorageWriteApiStreams());
+ fieldValues.put(
+ "propagate_successful_storage_api_writes",
+ transform.getPropagateSuccessfulStorageApiWrites());
+ fieldValues.put("max_files_per_partition", transform.getMaxFilesPerPartition());
+ fieldValues.put("max_bytes_per_partition", transform.getMaxBytesPerPartition());
+ if (transform.getTriggeringFrequency() != null) {
+ fieldValues.put(
+ "triggerring_frequency",
+ Duration.ofMillis(transform.getTriggeringFrequency().getMillis()));
+ }
+ if (transform.getMethod() != null) {
+ fieldValues.put("method", toByteArray(transform.getMethod()));
+ }
+ if (transform.getLoadJobProjectId() != null) {
+ fieldValues.put("load_job_project_id", transform.getLoadJobProjectId());
+ }
+ if (transform.getFailedInsertRetryPolicy() != null) {
+ fieldValues.put(
+ "failed_insert_retry_policy", toByteArray(transform.getFailedInsertRetryPolicy()));
+ }
+ if (transform.getCustomGcsTempLocation() != null) {
+ fieldValues.put("custom_gcs_temp_location", transform.getCustomGcsTempLocation().get());
+ }
+ fieldValues.put("extended_error_info", transform.getExtendedErrorInfo());
+ if (transform.getSkipInvalidRows() != null) {
+ fieldValues.put("skip_invalid_rows", transform.getSkipInvalidRows());
+ }
+ if (transform.getIgnoreUnknownValues() != null) {
+ fieldValues.put("ignore_unknown_values", transform.getIgnoreUnknownValues());
+ }
+ if (transform.getIgnoreInsertIds() != null) {
+ fieldValues.put("ignore_insert_ids", transform.getIgnoreInsertIds());
+ }
+ fieldValues.put("max_retry_jobs", transform.getMaxRetryJobs());
+ if (transform.getPropagateSuccessful() != null) {
+ fieldValues.put("propagate_successful", transform.getPropagateSuccessful());
+ }
+ if (transform.getKmsKey() != null) {
+ fieldValues.put("kms_key", transform.getKmsKey());
+ }
+ if (transform.getPrimaryKey() != null) {
+ fieldValues.put("primary_key", transform.getPrimaryKey());
+ }
+ if (transform.getDefaultMissingValueInterpretation() != null) {
+ fieldValues.put(
+ "default_missing_value_interpretation",
+ toByteArray(transform.getDefaultMissingValueInterpretation()));
+ }
+ if (transform.getOptimizeWrites() != null) {
+ fieldValues.put("optimize_writes", transform.getOptimizeWrites());
+ }
+ if (transform.getUseBeamSchema() != null) {
+ fieldValues.put("use_beam_schema", transform.getUseBeamSchema());
+ }
+ if (transform.getAutoSharding() != null) {
+ fieldValues.put("auto_sharding", transform.getAutoSharding());
+ }
+ if (transform.getAutoSchemaUpdate() != null) {
+ fieldValues.put("auto_schema_update", transform.getAutoSchemaUpdate());
+ }
+ if (transform.getWriteProtosClass() != null) {
+ fieldValues.put("write_protos_class", toByteArray(transform.getWriteProtosClass()));
+ }
+ if (transform.getDirectWriteProtos() != null) {
+ fieldValues.put("direct_write_protos", transform.getDirectWriteProtos());
+ }
+ if (transform.getDeterministicRecordIdFn() != null) {
+ fieldValues.put(
+ "deterministic_record_id_fn", toByteArray(transform.getDeterministicRecordIdFn()));
+ }
+ if (transform.getWriteTempDataset() != null) {
+ fieldValues.put("write_temp_dataset", toByteArray(transform.getDeterministicRecordIdFn()));
+ }
+ if (transform.getRowMutationInformationFn() != null) {
+ fieldValues.put(
+ "row_mutation_information_fn", toByteArray(transform.getRowMutationInformationFn()));
+ }
+
+ return Row.withSchema(schema).withFieldValues(fieldValues).build();
+ }
+
+ @Override
+ public Write<?> fromConfigRow(Row configRow) {
+ BigQueryIO.Write.Builder builder = new AutoValue_BigQueryIO_Write.Builder<>();
+
+ String jsonTableRef = configRow.getString("json_table_ref");
+ if (jsonTableRef != null) {
+ builder = builder.setJsonTableRef(StaticValueProvider.of(jsonTableRef));
+ }
+ byte[] tableFunctionBytes = configRow.getBytes("table_function");
+ if (tableFunctionBytes != null) {
+ builder =
+ builder.setTableFunction(
+ (SerializableFunction<ValueInSingleWindow, TableDestination>)
+ fromByteArray(tableFunctionBytes));
+ }
+ byte[] formatFunctionBytes = configRow.getBytes("format_function");
+ if (formatFunctionBytes != null) {
+ builder =
+ builder.setFormatFunction(
+ (SerializableFunction<?, TableRow>) fromByteArray(formatFunctionBytes));
+ }
+ byte[] formatRecordOnFailureFunctionBytes =
+ configRow.getBytes("format_record_on_failure_function");
+ if (tableFunctionBytes != null) {
+ builder =
+ builder.setFormatRecordOnFailureFunction(
+ (SerializableFunction<?, TableRow>)
+ fromByteArray(formatRecordOnFailureFunctionBytes));
+ }
+ byte[] avroRowWriterFactoryBytes = configRow.getBytes("avro_row_writer_factory");
+ if (avroRowWriterFactoryBytes != null) {
+ builder =
+ builder.setAvroRowWriterFactory(
+ (AvroRowWriterFactory) fromByteArray(avroRowWriterFactoryBytes));
+ }
+ byte[] avroSchemaFactoryBytes = configRow.getBytes("avro_schema_factory");
+ if (tableFunctionBytes != null) {
+ builder =
+ builder.setAvroSchemaFactory(
+ (SerializableFunction) fromByteArray(avroSchemaFactoryBytes));
+ }
+ Boolean useAvroLogicalTypes = configRow.getBoolean("use_avro_logical_types");
+ if (useAvroLogicalTypes != null) {
+ builder = builder.setUseAvroLogicalTypes(useAvroLogicalTypes);
+ }
+ byte[] dynamicDestinationsBytes = configRow.getBytes("dynamic_destinations");
+ if (dynamicDestinationsBytes != null) {
+ builder =
+ builder.setDynamicDestinations(
+ (DynamicDestinations) fromByteArray(dynamicDestinationsBytes));
+ }
+ String jsonSchema = configRow.getString("json_schema");
+ if (jsonSchema != null) {
+ builder = builder.setJsonSchema(StaticValueProvider.of(jsonSchema));
+ }
+ String jsonTimePartitioning = configRow.getString("json_time_partitioning");
+ if (jsonTimePartitioning != null) {
+ builder = builder.setJsonTimePartitioning(StaticValueProvider.of(jsonTimePartitioning));
+ }
+ byte[] clusteringBytes = configRow.getBytes("clustering");
+ if (clusteringBytes != null) {
+ builder = builder.setClustering((Clustering) fromByteArray(clusteringBytes));
+ }
+ byte[] createDispositionBytes = configRow.getBytes("create_disposition");
+ if (createDispositionBytes != null) {
+ builder =
+ builder.setCreateDisposition((CreateDisposition) fromByteArray(createDispositionBytes));
+ }
+ byte[] writeDispositionBytes = configRow.getBytes("write_disposition");
+ if (writeDispositionBytes != null) {
+ builder =
+ builder.setWriteDisposition((WriteDisposition) fromByteArray(writeDispositionBytes));
+ }
+ Collection<byte[]> schemaUpdateOptionsData = configRow.getArray("schema_update_options");
+ if (schemaUpdateOptionsData != null) {
+ Set<SchemaUpdateOption> schemaUpdateOptions =
+ schemaUpdateOptionsData.stream()
+ .map(data -> (SchemaUpdateOption) fromByteArray(data))
+ .collect(Collectors.toSet());
+ builder = builder.setSchemaUpdateOptions(schemaUpdateOptions);
+ } else {
+ // This property is not nullable.
+ builder = builder.setSchemaUpdateOptions(Collections.emptySet());
+ }
+ String tableDescription = configRow.getString("table_description");
+ if (tableDescription != null) {
+ builder = builder.setTableDescription(tableDescription);
+ }
+ Boolean validate = configRow.getBoolean("validate");
+ if (validate != null) {
+ builder = builder.setValidate(validate);
+ }
+ byte[] bigqueryServicesBytes = configRow.getBytes("bigquery_services");
+ if (bigqueryServicesBytes != null) {
+ builder =
+ builder.setBigQueryServices((BigQueryServices) fromByteArray(bigqueryServicesBytes));
+ }
+ Integer maxFilesPerBundle = configRow.getInt32("max_files_per_bundle");
+ if (maxFilesPerBundle != null) {
+ builder = builder.setMaxFilesPerBundle(maxFilesPerBundle);
+ }
+ Long maxFileSize = configRow.getInt64("max_file_size");
+ if (maxFileSize != null) {
+ builder = builder.setMaxFileSize(maxFileSize);
+ }
+ Integer numFileShards = configRow.getInt32("num_file_shards");
+ if (numFileShards != null) {
+ builder = builder.setNumFileShards(numFileShards);
+ }
+ Integer numStorageWriteApiStreams = configRow.getInt32("num_storage_write_api_streams");
+ if (numStorageWriteApiStreams != null) {
+ builder = builder.setNumStorageWriteApiStreams(numStorageWriteApiStreams);
+ }
+ Boolean propagateSuccessfulStorageApiWrites =
+ configRow.getBoolean("propagate_successful_storage_api_writes");
+ if (propagateSuccessfulStorageApiWrites != null) {
+ builder =
+ builder.setPropagateSuccessfulStorageApiWrites(propagateSuccessfulStorageApiWrites);
+ }
+ Integer maxFilesPerPartition = configRow.getInt32("max_files_per_partition");
+ if (maxFilesPerPartition != null) {
+ builder = builder.setMaxFilesPerPartition(maxFilesPerPartition);
+ }
+ Long maxBytesPerPartition = configRow.getInt64("max_bytes_per_partition");
+ if (maxBytesPerPartition != null) {
+ builder = builder.setMaxBytesPerPartition(maxBytesPerPartition);
+ }
+ Duration triggerringFrequency = configRow.getValue("triggerring_frequency");
+ if (triggerringFrequency != null) {
+ builder =
+ builder.setTriggeringFrequency(
+ org.joda.time.Duration.millis(triggerringFrequency.toMillis()));
+ }
+ byte[] methodBytes = configRow.getBytes("method");
+ if (methodBytes != null) {
+ builder = builder.setMethod((Write.Method) fromByteArray(methodBytes));
+ }
+ String loadJobProjectId = configRow.getString("load_job_project_id");
+ if (loadJobProjectId != null) {
+ builder = builder.setLoadJobProjectId(StaticValueProvider.of(loadJobProjectId));
+ }
+ byte[] failedInsertRetryPolicyBytes = configRow.getBytes("failed_insert_retry_policy");
+ if (failedInsertRetryPolicyBytes != null) {
+ builder =
+ builder.setFailedInsertRetryPolicy(
+ (InsertRetryPolicy) fromByteArray(failedInsertRetryPolicyBytes));
+ }
+ String customGcsTempLocations = configRow.getString("custom_gcs_temp_location");
+ if (customGcsTempLocations != null) {
+ builder = builder.setCustomGcsTempLocation(StaticValueProvider.of(customGcsTempLocations));
+ }
+ Boolean extendedErrorInfo = configRow.getBoolean("extended_error_info");
+ if (extendedErrorInfo != null) {
+ builder = builder.setExtendedErrorInfo(extendedErrorInfo);
+ }
+ Boolean skipInvalidRows = configRow.getBoolean("skip_invalid_rows");
+ if (skipInvalidRows != null) {
+ builder = builder.setSkipInvalidRows(skipInvalidRows);
+ }
+ Boolean ignoreUnknownValues = configRow.getBoolean("ignore_unknown_values");
+ if (ignoreUnknownValues != null) {
+ builder = builder.setIgnoreUnknownValues(ignoreUnknownValues);
+ }
+ Boolean ignoreInsertIds = configRow.getBoolean("ignore_insert_ids");
+ if (ignoreInsertIds != null) {
+ builder = builder.setIgnoreInsertIds(ignoreInsertIds);
+ }
+ Integer maxRetryJobs = configRow.getInt32("max_retry_jobs");
+ if (maxRetryJobs != null) {
+ builder = builder.setMaxRetryJobs(maxRetryJobs);
+ }
+ String kmsKey = configRow.getString("kms_key");
+ if (kmsKey != null) {
+ builder = builder.setKmsKey(kmsKey);
+ }
+ Collection<String> primaryKey = configRow.getArray("primary_key");
+ if (primaryKey != null && !primaryKey.isEmpty()) {
+ builder = builder.setPrimaryKey(ImmutableList.of(primaryKey));
+ }
+ byte[] defaultMissingValueInterpretationsBytes =
+ configRow.getBytes("default_missing_value_interpretation");
+ if (defaultMissingValueInterpretationsBytes != null) {
+ builder =
+ builder.setDefaultMissingValueInterpretation(
+ (MissingValueInterpretation)
+ fromByteArray(defaultMissingValueInterpretationsBytes));
+ }
+ Boolean optimizeWrites = configRow.getBoolean("optimize_writes");
+ if (optimizeWrites != null) {
+ builder = builder.setOptimizeWrites(optimizeWrites);
+ }
+ Boolean useBeamSchema = configRow.getBoolean("use_beam_schema");
+ if (useBeamSchema != null) {
+ builder = builder.setUseBeamSchema(useBeamSchema);
+ }
+ Boolean autoSharding = configRow.getBoolean("auto_sharding");
+ if (autoSharding != null) {
+ builder = builder.setAutoSharding(autoSharding);
+ }
+ Boolean propagateSuccessful = configRow.getBoolean("propagate_successful");
+ if (propagateSuccessful != null) {
+ builder = builder.setPropagateSuccessful(propagateSuccessful);
+ }
+ Boolean autoSchemaUpdate = configRow.getBoolean("auto_schema_update");
+ if (autoSchemaUpdate != null) {
+ builder = builder.setAutoSchemaUpdate(autoSchemaUpdate);
+ }
+ byte[] writeProtosClasses = configRow.getBytes("write_protos_class");
+ if (writeProtosClasses != null) {
+ builder =
+ builder.setWriteProtosClass(
+ (Class) fromByteArray(defaultMissingValueInterpretationsBytes));
+ }
+ Boolean directWriteProtos = configRow.getBoolean("direct_write_protos");
+ if (directWriteProtos != null) {
+ builder = builder.setDirectWriteProtos(directWriteProtos);
+ }
+ byte[] deterministicRecordIdFnBytes = configRow.getBytes("deterministic_record_id_fn");
+ if (deterministicRecordIdFnBytes != null) {
+ builder =
+ builder.setDeterministicRecordIdFn(
+ (SerializableFunction) fromByteArray(deterministicRecordIdFnBytes));
+ }
+ String writeTempDataset = configRow.getString("write_temp_dataset");
+ if (writeTempDataset != null) {
+ builder = builder.setWriteTempDataset(writeTempDataset);
+ }
+ byte[] rowMutationInformationFnBytes = configRow.getBytes("row_mutation_information_fn");
+ if (rowMutationInformationFnBytes != null) {
+ builder =
+ builder.setRowMutationInformationFn(
+ (SerializableFunction) fromByteArray(rowMutationInformationFnBytes));
+ }
+
+ return builder.build();
+ }
+ }
+
+ @AutoService(TransformPayloadTranslatorRegistrar.class)
+ public static class WriteRegistrar implements TransformPayloadTranslatorRegistrar {
+
+ @Override
+ @SuppressWarnings({
+ "rawtypes",
+ })
+ public Map<? extends Class<? extends PTransform>, ? extends TransformPayloadTranslator>
+ getTransformPayloadTranslators() {
+ return ImmutableMap.<Class<? extends PTransform>, TransformPayloadTranslator>builder()
+ .put(AutoValue_BigQueryIO_Write.class, new BigQueryIOWriteTranslator())
+ .build();
+ }
+ }
+}
diff --git a/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslationTest.java b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslationTest.java
new file mode 100644
index 00000000000..9de3b02c253
--- /dev/null
+++ b/sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIOTranslationTest.java
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.sdk.io.gcp.bigquery;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import com.google.api.services.bigquery.model.TableRow;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition;
+import org.apache.beam.sdk.transforms.SerializableFunction;
+import org.apache.beam.sdk.values.Row;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.collect.ImmutableList;
+import org.junit.Test;
+
+public class BigQueryIOTranslationTest {
+
+ // A mapping from Read transform builder methods to the corresponding schema fields in
+ // KafkaIOTranslation.
+ static final Map<String, String> READ_TRANSFORM_SCHEMA_MAPPING = new HashMap<>();
+
+ static {
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getJsonTableRef", "json_table_ref");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getQuery", "query");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getValidate", "validate");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getFlattenResults", "flatten_results");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getUseLegacySql", "use_legacy_sql");
+ READ_TRANSFORM_SCHEMA_MAPPING.put(
+ "getWithTemplateCompatibility", "with_template_compatibility");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getBigQueryServices", "bigquery_services");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getParseFn", "parse_fn");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getDatumReaderFactory", "datum_reader_factory");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getQueryPriority", "query_priority");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getQueryLocation", "query_location");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getQueryTempDataset", "query_temp_dataset");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getMethod", "method");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getFormat", "format");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getSelectedFields", "selected_fields");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getRowRestriction", "row_restriction");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getCoder", "coder");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getKmsKey", "kms_key");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getTypeDescriptor", "type_descriptor");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getToBeamRowFn", "to_beam_row_fn");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getFromBeamRowFn", "from_beam_row_fn");
+ READ_TRANSFORM_SCHEMA_MAPPING.put("getUseAvroLogicalTypes", "use_avro_logical_types");
+ READ_TRANSFORM_SCHEMA_MAPPING.put(
+ "getProjectionPushdownApplied", "projection_pushdown_applied");
+ }
+
+ static final Map<String, String> WRITE_TRANSFORM_SCHEMA_MAPPING = new HashMap<>();
+
+ static {
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getJsonTableRef", "json_table_ref");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getTableFunction", "table_function");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getFormatFunction", "format_function");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put(
+ "getFormatRecordOnFailureFunction", "format_record_on_failure_function");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getAvroRowWriterFactory", "avro_row_writer_factory");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getAvroSchemaFactory", "avro_schema_factory");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getUseAvroLogicalTypes", "use_avro_logical_types");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getDynamicDestinations", "dynamic_destinations");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getJsonSchema", "json_schema");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getJsonTimePartitioning", "json_time_partitioning");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getClustering", "clustering");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getCreateDisposition", "create_disposition");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getWriteDisposition", "write_disposition");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getSchemaUpdateOptions", "schema_update_options");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getTableDescription", "table_description");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getValidate", "validate");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getBigQueryServices", "bigquery_services");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMaxFilesPerBundle", "max_files_per_bundle");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMaxFileSize", "max_file_size");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getNumFileShards", "num_file_shards");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put(
+ "getNumStorageWriteApiStreams", "num_storage_write_api_streams");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put(
+ "getPropagateSuccessfulStorageApiWrites", "propagate_successful_storage_api_writes");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMaxFilesPerPartition", "max_files_per_partition");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMaxBytesPerPartition", "max_bytes_per_partition");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getTriggeringFrequency", "triggerring_frequency");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMethod", "method");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getLoadJobProjectId", "load_job_project_id");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getFailedInsertRetryPolicy", "failed_insert_retry_policy");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getCustomGcsTempLocation", "custom_gcs_temp_location");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getExtendedErrorInfo", "extended_error_info");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getSkipInvalidRows", "skip_invalid_rows");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getIgnoreUnknownValues", "ignore_unknown_values");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getIgnoreInsertIds", "ignore_insert_ids");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getMaxRetryJobs", "max_retry_jobs");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getKmsKey", "kms_key");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getPrimaryKey", "primary_key");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put(
+ "getDefaultMissingValueInterpretation", "default_missing_value_interpretation");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getOptimizeWrites", "optimize_writes");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getUseBeamSchema", "use_beam_schema");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getAutoSharding", "auto_sharding");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getPropagateSuccessful", "propagate_successful");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getAutoSchemaUpdate", "auto_schema_update");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getWriteProtosClass", "write_protos_class");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getDirectWriteProtos", "direct_write_protos");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getDeterministicRecordIdFn", "deterministic_record_id_fn");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put("getWriteTempDataset", "write_temp_dataset");
+ WRITE_TRANSFORM_SCHEMA_MAPPING.put(
+ "getRowMutationInformationFn", "row_mutation_information_fn");
+ }
+
+ @Test
+ public void testReCreateReadTransformFromRowTable() {
+ // setting a subset of fields here.
+ BigQueryIO.TypedRead<TableRow> readTransform =
+ BigQueryIO.readTableRows()
+ .from("dummyproject:dummydataset.dummytable")
+ .withMethod(TypedRead.Method.DIRECT_READ)
+ .withKmsKey("dummykmskey")
+ .withTemplateCompatibility();
+
+ BigQueryIOTranslation.BigQueryIOReadTranslator translator =
+ new BigQueryIOTranslation.BigQueryIOReadTranslator();
+ Row row = translator.toConfigRow(readTransform);
+
+ BigQueryIO.TypedRead<TableRow> readTransformFromRow =
+ (BigQueryIO.TypedRead<TableRow>) translator.fromConfigRow(row);
+ assertNotNull(readTransformFromRow.getTable());
+ assertEquals("dummyproject", readTransformFromRow.getTable().getProjectId());
+ assertEquals("dummydataset", readTransformFromRow.getTable().getDatasetId());
+ assertEquals("dummytable", readTransformFromRow.getTable().getTableId());
+ assertEquals(TypedRead.Method.DIRECT_READ, readTransformFromRow.getMethod());
+ assertEquals("dummykmskey", readTransformFromRow.getKmsKey());
+ assertTrue(readTransformFromRow.getWithTemplateCompatibility());
+ }
+
+ static class DummyParseFn implements SerializableFunction<SchemaAndRecord, Object> {
+ @Override
+ public Object apply(SchemaAndRecord input) {
+ return null;
+ }
+ }
+
+ @Test
+ public void testReCreateReadTransformFromRowQuery() {
+ // setting a subset of fields here.
+ BigQueryIO.TypedRead<?> readTransform =
+ BigQueryIO.read(new DummyParseFn())
+ .fromQuery("dummyquery")
+ .useAvroLogicalTypes()
+ .usingStandardSql();
+
+ BigQueryIOTranslation.BigQueryIOReadTranslator translator =
+ new BigQueryIOTranslation.BigQueryIOReadTranslator();
+ Row row = translator.toConfigRow(readTransform);
+
+ BigQueryIO.TypedRead<?> readTransformFromRow = translator.fromConfigRow(row);
+ assertEquals("dummyquery", readTransformFromRow.getQuery().get());
+ assertNotNull(readTransformFromRow.getParseFn());
+ assertTrue(readTransformFromRow.getParseFn() instanceof DummyParseFn);
+ assertTrue(readTransformFromRow.getUseAvroLogicalTypes());
+ assertFalse(readTransformFromRow.getUseLegacySql());
+ }
+
+ @Test
+ public void testReadTransformRowIncludesAllFields() {
+ // These fields do not represent properties of the transform.
+ List<String> fieldsToIgnore =
+ ImmutableList.of("getFinalSchema", "getTableProvider", "getTable");
+
+ List<String> getMethodNames =
+ Arrays.stream(BigQueryIO.TypedRead.class.getDeclaredMethods())
+ .map(
+ method -> {
+ return method.getName();
+ })
+ .filter(methodName -> methodName.startsWith("get"))
+ .filter(methodName -> !fieldsToIgnore.contains(methodName))
+ .collect(Collectors.toList());
+
+ // Just to make sure that this does not pass trivially.
+ assertTrue(getMethodNames.size() > 0);
+
+ for (String getMethodName : getMethodNames) {
+ assertTrue(
+ "Method "
+ + getMethodName
+ + " will not be tracked when upgrading the 'BigQueryIO.TypedRead' transform. Please update"
+ + "'BigQueryIOTranslation.BigQueryIOReadTranslator' to track the new method "
+ + "and update this test.",
+ READ_TRANSFORM_SCHEMA_MAPPING.keySet().contains(getMethodName));
+ }
+
+ // Confirming that all fields mentioned in `READ_TRANSFORM_SCHEMA_MAPPING` are
+ // actually available in the schema.
+ READ_TRANSFORM_SCHEMA_MAPPING.values().stream()
+ .forEach(
+ fieldName -> {
+ assertTrue(
+ "Field name "
+ + fieldName
+ + " was not found in the transform schema defined in "
+ + "BigQueryIOTranslation.BigQueryIOReadTranslator.",
+ BigQueryIOTranslation.BigQueryIOReadTranslator.schema
+ .getFieldNames()
+ .contains(fieldName));
+ });
+ }
+
+ @Test
+ public void testReCreateWriteTransformFromRowTable() {
+ // setting a subset of fields here.
+ BigQueryIO.Write<?> writeTransform =
+ BigQueryIO.write()
+ .to("dummyproject:dummydataset.dummytable")
+ .withAutoSharding()
+ .withTriggeringFrequency(org.joda.time.Duration.millis(10000))
+ .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)
+ .withCreateDisposition(CreateDisposition.CREATE_NEVER)
+ .withKmsKey("dummykmskey");
+
+ BigQueryIOTranslation.BigQueryIOWriteTranslator translator =
+ new BigQueryIOTranslation.BigQueryIOWriteTranslator();
+ Row row = translator.toConfigRow(writeTransform);
+
+ BigQueryIO.Write<?> writeTransformFromRow = (BigQueryIO.Write<?>) translator.fromConfigRow(row);
+ assertNotNull(writeTransformFromRow.getTable());
+ assertEquals("dummyproject", writeTransformFromRow.getTable().get().getProjectId());
+ assertEquals("dummydataset", writeTransformFromRow.getTable().get().getDatasetId());
+ assertEquals("dummytable", writeTransformFromRow.getTable().get().getTableId());
+ assertEquals(WriteDisposition.WRITE_TRUNCATE, writeTransformFromRow.getWriteDisposition());
+ assertEquals(CreateDisposition.CREATE_NEVER, writeTransformFromRow.getCreateDisposition());
+ assertEquals("dummykmskey", writeTransformFromRow.getKmsKey());
+ }
+
+ @Test
+ public void testWriteTransformRowIncludesAllFields() {
+ // These fields do not represent properties of the transform.
+ List<String> fieldsToIgnore =
+ ImmutableList.of(
+ "getSchemaFromView",
+ "getStorageApiNumStreams",
+ "getStorageApiTriggeringFrequency",
+ "getTableWithDefaultProject",
+ "getTable");
+
+ List<String> getMethodNames =
+ Arrays.stream(BigQueryIO.Write.class.getDeclaredMethods())
+ .map(
+ method -> {
+ return method.getName();
+ })
+ .filter(methodName -> methodName.startsWith("get"))
+ .filter(methodName -> !fieldsToIgnore.contains(methodName))
+ .collect(Collectors.toList());
+
+ // Just to make sure that this does not pass trivially.
+ assertTrue(getMethodNames.size() > 0);
+
+ for (String getMethodName : getMethodNames) {
+ assertTrue(
+ "Method "
+ + getMethodName
+ + " will not be tracked when upgrading the 'BigQueryIO.Write' transform. Please update"
+ + "'BigQueryIOTranslation.BigQueryIOWriteTranslator' to track the new method "
+ + "and update this test.",
+ WRITE_TRANSFORM_SCHEMA_MAPPING.keySet().contains(getMethodName));
+ }
+
+ // Confirming that all fields mentioned in `WRITE_TRANSFORM_SCHEMA_MAPPING` are
+ // actually available in the schema.
+ WRITE_TRANSFORM_SCHEMA_MAPPING.values().stream()
+ .forEach(
+ fieldName -> {
+ assertTrue(
+ "Field name "
+ + fieldName
+ + " was not found in the transform schema defined in "
+ + "BigQueryIOTranslation.BigQueryIOWriteTranslator.",
+ BigQueryIOTranslation.BigQueryIOWriteTranslator.schema
+ .getFieldNames()
+ .contains(fieldName));
+ });
+ }
+}
diff --git a/sdks/java/io/kafka/upgrade/src/main/java/org/apache/beam/sdk/io/kafka/upgrade/KafkaIOTranslation.java b/sdks/java/io/kafka/upgrade/src/main/java/org/apache/beam/sdk/io/kafka/upgrade/KafkaIOTranslation.java
index 1757da6a631..16580cd219b 100644
--- a/sdks/java/io/kafka/upgrade/src/main/java/org/apache/beam/sdk/io/kafka/upgrade/KafkaIOTranslation.java
+++ b/sdks/java/io/kafka/upgrade/src/main/java/org/apache/beam/sdk/io/kafka/upgrade/KafkaIOTranslation.java
@@ -17,12 +17,11 @@
*/
package org.apache.beam.sdk.io.kafka.upgrade;
+import static org.apache.beam.runners.core.construction.TransformUpgrader.fromByteArray;
+import static org.apache.beam.runners.core.construction.TransformUpgrader.toByteArray;
+
import com.google.auto.service.AutoService;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
@@ -73,25 +72,6 @@ public class KafkaIOTranslation {
public static final String KAFKA_WRITE_TRANSFORM_URN_V2 =
"beam:transform:org.apache.beam:kafka_write:v2";
- private static byte[] toByteArray(Object object) {
- try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream out = new ObjectOutputStream(bos)) {
- out.writeObject(object);
- return bos.toByteArray();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private static Object fromByteArray(byte[] bytes) {
- try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
- ObjectInputStream in = new ObjectInputStream(bis)) {
- return in.readObject();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
static class KafkaIOReadWithMetadataTranslator implements TransformPayloadTranslator<Read<?, ?>> {
static Schema topicPartitionSchema =