ahmedabu98 commented on code in PR #29114:
URL: https://github.com/apache/beam/pull/29114#discussion_r1370710789


##########
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiSinkDefaultValuesIT.java:
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import com.google.api.services.bigquery.model.Table;
+import com.google.api.services.bigquery.model.TableFieldSchema;
+import com.google.api.services.bigquery.model.TableReference;
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.api.services.bigquery.model.TableSchema;
+import com.google.cloud.bigquery.storage.v1.AppendRowsRequest;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
+import org.apache.beam.sdk.io.gcp.testing.BigqueryClient;
+import org.apache.beam.sdk.testing.TestPipeline;
+import org.apache.beam.sdk.transforms.Create;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.values.PCollection;
+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.Lists;
+import org.joda.time.Duration;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StorageApiSinkDefaultValuesIT {
+  private static final BigqueryClient BQ_CLIENT =
+      new BigqueryClient("StorageApiSinkDefaultValuesIT");
+  private static final String PROJECT =
+      TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject();
+  private static final String BIG_QUERY_DATASET_ID =
+      "storage_api_sink_default_values" + System.nanoTime();
+
+  private static String bigQueryLocation;
+
+  @BeforeClass
+  public static void setUpTestEnvironment() throws IOException, 
InterruptedException {
+    // Create one BQ dataset for all test cases.
+    bigQueryLocation =
+        
TestPipeline.testingPipelineOptions().as(TestBigQueryOptions.class).getBigQueryLocation();
+    BQ_CLIENT.createNewDataset(PROJECT, BIG_QUERY_DATASET_ID, null, 
bigQueryLocation);
+  }
+
+  @AfterClass
+  public static void cleanup() {
+    BQ_CLIENT.deleteDataset(PROJECT, BIG_QUERY_DATASET_ID);
+  }
+
+  private static String createAndGetTablespec(TableSchema tableSchema)
+      throws IOException, InterruptedException {
+    String tableName = "table" + System.nanoTime();
+    TableReference tableReference =
+        new TableReference()
+            .setProjectId(PROJECT)
+            .setDatasetId(BIG_QUERY_DATASET_ID)
+            .setTableId(tableName);
+    BQ_CLIENT.createNewTable(
+        PROJECT,
+        BIG_QUERY_DATASET_ID,
+        new Table().setSchema(tableSchema).setTableReference(tableReference));
+    return PROJECT + "." + BIG_QUERY_DATASET_ID + "." + tableName;
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeDefault() throws IOException, 
InterruptedException {
+    runTest(true, true, false);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaKnownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(true, true, true);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaUnknownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(false, true, true);
+  }
+
+  @Test
+  public void testMissingValueSchemaUnknownTakeDefault() throws IOException, 
InterruptedException {
+
+    runTest(false, true, false);
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeNull() throws IOException, 
InterruptedException {
+    runTest(true, false, false);
+  }
+
+  @Test
+  @Ignore // This currently appears broke in BigQuery.
+  public void testMissingValueSchemaUnknownTakeNull() throws IOException, 
InterruptedException {
+    runTest(false, false, false);
+  }
+
+  public void runTest(
+      boolean sinkKnowsDefaultFields, boolean takeDefault, boolean 
defaultFieldsRequired)
+      throws IOException, InterruptedException {
+    TableSchema bqSchema;
+    if (defaultFieldsRequired) {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42")
+                          .setMode("REQUIRED"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")
+                          .setMode("REQUIRED")));
+    } else {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")));
+    }
+
+    TableSchema sinkSchema = bqSchema;
+    if (!sinkKnowsDefaultFields) {
+      sinkSchema =
+          new TableSchema()
+              .setFields(
+                  bqSchema.getFields().stream()
+                      .filter(tfs -> tfs.getDefaultValueExpression() == null)
+                      .collect(Collectors.toList()));
+    }
+    final TableRow row1 =
+        new TableRow()
+            .set("id", "row1")
+            .set("key2", "bar0")
+            .set("value", "1")
+            .set("defaultliteral", 12);
+    final TableRow row2 = new TableRow().set("id", "row2").set("key2", 
"bar1").set("value", "1");
+    final TableRow row3 = new TableRow().set("id", "row3").set("key2", 
"bar2").set("value", "2");
+
+    List<TableRow> tableRows = Lists.newArrayList(row1, row2, row3);
+
+    String tableSpec = createAndGetTablespec(bqSchema);
+    Pipeline p = Pipeline.create();
+
+    BigQueryIO.Write<TableRow> write =
+        BigQueryIO.writeTableRows()
+            .to(tableSpec)
+            .withSchema(sinkSchema)
+            .withNumStorageWriteApiStreams(2)
+            .ignoreUnknownValues()
+            .withTriggeringFrequency(Duration.standardSeconds(1))
+            .withMethod(BigQueryIO.Write.Method.STORAGE_WRITE_API)
+            
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER);
+    if (!takeDefault) {
+      write =
+          write.withDefaultMissingValueInterpretation(
+              AppendRowsRequest.MissingValueInterpretation.NULL_VALUE);
+    }
+    p.apply("Create rows", Create.of(tableRows))
+        .setIsBoundedInternal(PCollection.IsBounded.UNBOUNDED)
+        .apply("write", write);
+    p.run();
+
+    Map<String, TableRow> queryResponse =
+        BQ_CLIENT
+            .queryUnflattened(
+                String.format("SELECT * FROM %s", tableSpec), PROJECT, true, 
true, bigQueryLocation)
+            .stream()
+            .collect(Collectors.toMap(tr -> (String) tr.get("id"), 
Function.identity()));
+    assertThat(queryResponse.size(), equalTo(3));
+    System.err.println("MAP IS " + queryResponse);

Review Comment:
   nit: cleanup



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java:
##########
@@ -2143,6 +2144,8 @@ public static <T> Write<T> write() {
         .setMaxRetryJobs(1000)
         .setPropagateSuccessfulStorageApiWrites(false)
         .setDirectWriteProtos(true)
+        .setDefaultMissingValueInterpretation(
+            AppendRowsRequest.MissingValueInterpretation.DEFAULT_VALUE)

Review Comment:
   the old behavior would set missing values as `null`. Looking at [BQ 
docs](https://cloud.google.com/java/docs/reference/google-cloud-bigquerystorage/2.38.0/com.google.cloud.bigquery.storage.v1.AppendRowsRequest.MissingValueInterpretation),
 if DEFAULT_VALUE is set but there is no default actually declared on the 
schema, it will write a null value.
   
   The only affected case is for users that declared a default value. Instead 
of writing missing values as null, the sink would now write the default value. 
In that sense, this is probably more of a "bug fix" than a breaking change?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java:
##########
@@ -213,10 +213,15 @@ private static String 
getPrettyFieldName(SchemaInformation schema) {
           .put(TableFieldSchema.Type.JSON, "JSON")
           .build();
 
-  public static TableFieldSchema.Mode modeToProtoMode(String mode) {
+  public static TableFieldSchema.Mode modeToProtoMode(
+      @Nullable String defaultValueExpression, String mode) {
+    // If there is a default value expression, treat this field as if it were 
nullable.
+    if (defaultValueExpression != null) {
+      return TableFieldSchema.Mode.NULLABLE;
+    }

Review Comment:
   Should this also depend on the specified `MissingValueInterpretation`? For 
example if one chooses 
`MissingValueInterpretation.MISSING_VALUE_INTERPRETATION_UNSPECIFIED`, should 
we be keeping the field as required?
   
   Also, how does this play out if the field's original mode is `REPEATED`?



##########
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiSinkDefaultValuesIT.java:
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import com.google.api.services.bigquery.model.Table;
+import com.google.api.services.bigquery.model.TableFieldSchema;
+import com.google.api.services.bigquery.model.TableReference;
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.api.services.bigquery.model.TableSchema;
+import com.google.cloud.bigquery.storage.v1.AppendRowsRequest;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
+import org.apache.beam.sdk.io.gcp.testing.BigqueryClient;
+import org.apache.beam.sdk.testing.TestPipeline;
+import org.apache.beam.sdk.transforms.Create;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.values.PCollection;
+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.Lists;
+import org.joda.time.Duration;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StorageApiSinkDefaultValuesIT {
+  private static final BigqueryClient BQ_CLIENT =
+      new BigqueryClient("StorageApiSinkDefaultValuesIT");
+  private static final String PROJECT =
+      TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject();
+  private static final String BIG_QUERY_DATASET_ID =
+      "storage_api_sink_default_values" + System.nanoTime();
+
+  private static String bigQueryLocation;
+
+  @BeforeClass
+  public static void setUpTestEnvironment() throws IOException, 
InterruptedException {
+    // Create one BQ dataset for all test cases.
+    bigQueryLocation =
+        
TestPipeline.testingPipelineOptions().as(TestBigQueryOptions.class).getBigQueryLocation();
+    BQ_CLIENT.createNewDataset(PROJECT, BIG_QUERY_DATASET_ID, null, 
bigQueryLocation);
+  }
+
+  @AfterClass
+  public static void cleanup() {
+    BQ_CLIENT.deleteDataset(PROJECT, BIG_QUERY_DATASET_ID);
+  }
+
+  private static String createAndGetTablespec(TableSchema tableSchema)
+      throws IOException, InterruptedException {
+    String tableName = "table" + System.nanoTime();
+    TableReference tableReference =
+        new TableReference()
+            .setProjectId(PROJECT)
+            .setDatasetId(BIG_QUERY_DATASET_ID)
+            .setTableId(tableName);
+    BQ_CLIENT.createNewTable(
+        PROJECT,
+        BIG_QUERY_DATASET_ID,
+        new Table().setSchema(tableSchema).setTableReference(tableReference));
+    return PROJECT + "." + BIG_QUERY_DATASET_ID + "." + tableName;
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeDefault() throws IOException, 
InterruptedException {
+    runTest(true, true, false);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaKnownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(true, true, true);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaUnknownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(false, true, true);
+  }
+
+  @Test
+  public void testMissingValueSchemaUnknownTakeDefault() throws IOException, 
InterruptedException {
+
+    runTest(false, true, false);
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeNull() throws IOException, 
InterruptedException {
+    runTest(true, false, false);
+  }
+
+  @Test
+  @Ignore // This currently appears broke in BigQuery.
+  public void testMissingValueSchemaUnknownTakeNull() throws IOException, 
InterruptedException {
+    runTest(false, false, false);
+  }
+
+  public void runTest(
+      boolean sinkKnowsDefaultFields, boolean takeDefault, boolean 
defaultFieldsRequired)
+      throws IOException, InterruptedException {
+    TableSchema bqSchema;
+    if (defaultFieldsRequired) {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42")
+                          .setMode("REQUIRED"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")
+                          .setMode("REQUIRED")));
+    } else {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")));
+    }
+
+    TableSchema sinkSchema = bqSchema;
+    if (!sinkKnowsDefaultFields) {
+      sinkSchema =
+          new TableSchema()
+              .setFields(
+                  bqSchema.getFields().stream()
+                      .filter(tfs -> tfs.getDefaultValueExpression() == null)
+                      .collect(Collectors.toList()));
+    }
+    final TableRow row1 =
+        new TableRow()
+            .set("id", "row1")
+            .set("key2", "bar0")
+            .set("value", "1")
+            .set("defaultliteral", 12);
+    final TableRow row2 = new TableRow().set("id", "row2").set("key2", 
"bar1").set("value", "1");
+    final TableRow row3 = new TableRow().set("id", "row3").set("key2", 
"bar2").set("value", "2");
+
+    List<TableRow> tableRows = Lists.newArrayList(row1, row2, row3);
+
+    String tableSpec = createAndGetTablespec(bqSchema);
+    Pipeline p = Pipeline.create();
+
+    BigQueryIO.Write<TableRow> write =
+        BigQueryIO.writeTableRows()
+            .to(tableSpec)
+            .withSchema(sinkSchema)
+            .withNumStorageWriteApiStreams(2)
+            .ignoreUnknownValues()

Review Comment:
   qq: is `ignoreUnknownValues` required to use missing value interpretation? 
or is it just added here so we can write the first row with "defaultliteral" 
missing from the schema?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java:
##########
@@ -2964,6 +2972,11 @@ public Write<T> withPrimaryKey(List<String> primaryKey) {
       return toBuilder().setPrimaryKey(primaryKey).build();
     }
 
+    public Write<T> withDefaultMissingValueInterpretation(

Review Comment:
   Would be helpful to add some documentation on what this does and what the 
possible enums are



##########
sdks/java/io/google-cloud-platform/src/test/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiSinkDefaultValuesIT.java:
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import com.google.api.services.bigquery.model.Table;
+import com.google.api.services.bigquery.model.TableFieldSchema;
+import com.google.api.services.bigquery.model.TableReference;
+import com.google.api.services.bigquery.model.TableRow;
+import com.google.api.services.bigquery.model.TableSchema;
+import com.google.cloud.bigquery.storage.v1.AppendRowsRequest;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.beam.sdk.Pipeline;
+import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
+import org.apache.beam.sdk.io.gcp.testing.BigqueryClient;
+import org.apache.beam.sdk.testing.TestPipeline;
+import org.apache.beam.sdk.transforms.Create;
+import org.apache.beam.sdk.util.Preconditions;
+import org.apache.beam.sdk.values.PCollection;
+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.Lists;
+import org.joda.time.Duration;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class StorageApiSinkDefaultValuesIT {
+  private static final BigqueryClient BQ_CLIENT =
+      new BigqueryClient("StorageApiSinkDefaultValuesIT");
+  private static final String PROJECT =
+      TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject();
+  private static final String BIG_QUERY_DATASET_ID =
+      "storage_api_sink_default_values" + System.nanoTime();
+
+  private static String bigQueryLocation;
+
+  @BeforeClass
+  public static void setUpTestEnvironment() throws IOException, 
InterruptedException {
+    // Create one BQ dataset for all test cases.
+    bigQueryLocation =
+        
TestPipeline.testingPipelineOptions().as(TestBigQueryOptions.class).getBigQueryLocation();
+    BQ_CLIENT.createNewDataset(PROJECT, BIG_QUERY_DATASET_ID, null, 
bigQueryLocation);
+  }
+
+  @AfterClass
+  public static void cleanup() {
+    BQ_CLIENT.deleteDataset(PROJECT, BIG_QUERY_DATASET_ID);
+  }
+
+  private static String createAndGetTablespec(TableSchema tableSchema)
+      throws IOException, InterruptedException {
+    String tableName = "table" + System.nanoTime();
+    TableReference tableReference =
+        new TableReference()
+            .setProjectId(PROJECT)
+            .setDatasetId(BIG_QUERY_DATASET_ID)
+            .setTableId(tableName);
+    BQ_CLIENT.createNewTable(
+        PROJECT,
+        BIG_QUERY_DATASET_ID,
+        new Table().setSchema(tableSchema).setTableReference(tableReference));
+    return PROJECT + "." + BIG_QUERY_DATASET_ID + "." + tableName;
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeDefault() throws IOException, 
InterruptedException {
+    runTest(true, true, false);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaKnownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(true, true, true);
+  }
+
+  @Test
+  public void testMissingRequiredValueSchemaUnknownTakeDefault()
+      throws IOException, InterruptedException {
+    runTest(false, true, true);
+  }
+
+  @Test
+  public void testMissingValueSchemaUnknownTakeDefault() throws IOException, 
InterruptedException {
+
+    runTest(false, true, false);
+  }
+
+  @Test
+  public void testMissingValueSchemaKnownTakeNull() throws IOException, 
InterruptedException {
+    runTest(true, false, false);
+  }
+
+  @Test
+  @Ignore // This currently appears broke in BigQuery.
+  public void testMissingValueSchemaUnknownTakeNull() throws IOException, 
InterruptedException {
+    runTest(false, false, false);
+  }
+
+  public void runTest(
+      boolean sinkKnowsDefaultFields, boolean takeDefault, boolean 
defaultFieldsRequired)
+      throws IOException, InterruptedException {
+    TableSchema bqSchema;
+    if (defaultFieldsRequired) {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42")
+                          .setMode("REQUIRED"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")
+                          .setMode("REQUIRED")));
+    } else {
+      bqSchema =
+          new TableSchema()
+              .setFields(
+                  ImmutableList.of(
+                      new TableFieldSchema().setName("id").setType("STRING"),
+                      new TableFieldSchema().setName("key2").setType("STRING"),
+                      new 
TableFieldSchema().setName("value").setType("STRING"),
+                      new TableFieldSchema()
+                          .setName("defaultliteral")
+                          .setType("INT64")
+                          .setDefaultValueExpression("42"),
+                      new TableFieldSchema()
+                          .setName("defaulttime")
+                          .setType("TIMESTAMP")
+                          .setDefaultValueExpression("CURRENT_TIMESTAMP()")));
+    }
+
+    TableSchema sinkSchema = bqSchema;
+    if (!sinkKnowsDefaultFields) {
+      sinkSchema =
+          new TableSchema()
+              .setFields(
+                  bqSchema.getFields().stream()
+                      .filter(tfs -> tfs.getDefaultValueExpression() == null)
+                      .collect(Collectors.toList()));
+    }
+    final TableRow row1 =
+        new TableRow()
+            .set("id", "row1")
+            .set("key2", "bar0")
+            .set("value", "1")
+            .set("defaultliteral", 12);
+    final TableRow row2 = new TableRow().set("id", "row2").set("key2", 
"bar1").set("value", "1");
+    final TableRow row3 = new TableRow().set("id", "row3").set("key2", 
"bar2").set("value", "2");
+
+    List<TableRow> tableRows = Lists.newArrayList(row1, row2, row3);
+
+    String tableSpec = createAndGetTablespec(bqSchema);
+    Pipeline p = Pipeline.create();
+
+    BigQueryIO.Write<TableRow> write =
+        BigQueryIO.writeTableRows()
+            .to(tableSpec)
+            .withSchema(sinkSchema)
+            .withNumStorageWriteApiStreams(2)
+            .ignoreUnknownValues()
+            .withTriggeringFrequency(Duration.standardSeconds(1))
+            .withMethod(BigQueryIO.Write.Method.STORAGE_WRITE_API)
+            
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER);
+    if (!takeDefault) {
+      write =
+          write.withDefaultMissingValueInterpretation(
+              AppendRowsRequest.MissingValueInterpretation.NULL_VALUE);

Review Comment:
   What happens when we specify `MISSING_VALUE_INTERPRETATION_UNSPECIFIED`?



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableRowToStorageApiProto.java:
##########
@@ -213,10 +213,15 @@ private static String 
getPrettyFieldName(SchemaInformation schema) {
           .put(TableFieldSchema.Type.JSON, "JSON")
           .build();
 
-  public static TableFieldSchema.Mode modeToProtoMode(String mode) {
+  public static TableFieldSchema.Mode modeToProtoMode(
+      @Nullable String defaultValueExpression, String mode) {
+    // If there is a default value expression, treat this field as if it were 
nullable.
+    if (defaultValueExpression != null) {
+      return TableFieldSchema.Mode.NULLABLE;
+    }

Review Comment:
   More broadly, is there a good reason to change the field's mode? One can 
argue that `REQUIRED` mode should remain strict, even in the presence of a 
default value.
   
   I don't have strong feelings about this but if we design it this way, it 
should be mentioned in the documentation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to