You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "jrmccluskey (via GitHub)" <gi...@apache.org> on 2026/07/07 15:10:42 UTC

[PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

jrmccluskey opened a new pull request, #39236:
URL: https://github.com/apache/beam/pull/39236

   Implements support for using dynamic schemas in StorageWriteToBigQuery invocations. 
   
   ------------------------
   
   Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
   
    - [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
    - [ ] Update `CHANGES.md` with noteworthy changes.
    - [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
   
   See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
   
   To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
   
   GitHub Actions Tests Status (on master branch)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/actions/workflows/build_wheels.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/actions/workflows/python_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/actions/workflows/java_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/actions/workflows/go_tests.yml/badge.svg?event=schedule&&?branch=master)](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
   
   See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6061385291

   R: @ahmedabu98 can you take a quick pass on this to make sure I am not missing anything/ that the general approach looks good?


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5588137694

   I started looking through it last week. Will leave comments soon.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6148133419

   > I'm a little iffy about this approach. It requires the input PCollection schema to be the full union of all destination table schemas. And the input schema is still fixed, so can't meet the need of new tables containing new columns, or existing table schema updates.
   > 
   > Also tables with identical column names will need to agree on their types and modes (e.g. table1 has colA as a nullable INT32 but table2 has colA as an array of Strings)
   > 
   > I think a more robust long term solution would need a semi-structured type like Variant so rows can include only what they need (see #38251)
   
   Yeah I haven't been thrilled with the options across the cross-language boundary, the core issue is that the row coder between the Python SDK and the Java SDK is fixed at pipeline construction time. Not being able to handle dynamic schemas kinda undercuts the whole point of dynamic destinations. I agree that the Variant type probably solves this for us, the only question is if we want to provide a "dynamic destinations, static schemas" version of this before we implement Variant (might unblock some use cases but will likely not be streaming update compatible since we'll be changing coders around.)


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-4916814521

   @gemini-code-assist review


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5138109705

   Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6039568445

   @claudevdm bump


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5683057035

   Gonna go back to the drawing board on the Java side here, there's definitely value in keeping the existing storage write API behavior unchanged


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5038523473

   > [!CAUTION]
   > The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-4917693550

   /gemini review


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-4916949674

   /gemini review


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-4917064280

   > [!WARNING]
   > Gemini encountered an error creating the review. You can try again by commenting `/gemini review`.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on code in PR #39236:
URL: https://github.com/apache/beam/pull/39236#discussion_r3725366522


##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -197,6 +197,43 @@ def compute_table_name(row):
 a tuple of PCollectionViews to be passed to the schema callable (much like
 the `table_side_inputs` parameter).
 
+Dynamic Schemas with Storage Write API
+--------------------------------------
+When writing to dynamic destinations with `method=STORAGE_WRITE_API`, a union schema
+containing all fields across destination tables is required at the PCollection level

Review Comment:
   Is the expectation that the destination schema for every table will be the full union schema, or each table is meant to have the individually mapped schema and union is just a trick to make it work? Can you add an integration test that validates the expected schema on the tables and document the expected behavior?



##########
.github/trigger_files/beam_PostCommit_Python_Xlang_Gcp_Dataflow.json:
##########
@@ -1,4 +1,4 @@
 {
   "comment": "Modify this file in a trivial way to cause this test suite to run",
-  "modification": 16
+  "modification": 21

Review Comment:
   I think you can also trigger .github/trigger_files/beam_PostCommit_Python_Xlang_Gcp_Direct.json for faster validation



##########
sdks/python/apache_beam/io/external/xlang_bigqueryio_it_test.py:
##########
@@ -483,6 +484,74 @@ def test_write_to_dynamic_destinations(self):
               use_at_least_once=False))
     hamcrest_assert(p, all_of(*bq_matchers))
 
+  def test_write_to_dynamic_destinations_with_dynamic_schema(self):

Review Comment:
   Can we add a test for the case where the destination tables are pre-created/ already exist beforehand? 



##########
sdks/python/apache_beam/io/external/xlang_bigqueryio_it_test.py:
##########
@@ -483,6 +484,74 @@ def test_write_to_dynamic_destinations(self):
               use_at_least_once=False))
     hamcrest_assert(p, all_of(*bq_matchers))
 
+  def test_write_to_dynamic_destinations_with_dynamic_schema(self):
+    base_table_spec = '{}.dynamic_dest_dyn_schema_'.format(self.dataset_id)
+    spec_with_project = '{}:{}'.format(self.project, base_table_spec)
+    table_a = base_table_spec + 'users'
+    table_b = base_table_spec + 'scores'
+
+    schema_a = "id:INTEGER,name:STRING"
+    schema_b = "id:INTEGER,score:INTEGER,active:BOOLEAN"
+
+    elements_a = [
+        {
+            'id': 1, 'name': 'alice'
+        },
+        {
+            'id': 2, 'name': 'bob'
+        },
+    ]
+    elements_b = [
+        {
+            'id': 101, 'score': 95, 'active': True
+        },
+        {
+            'id': 102, 'score': 80, 'active': False
+        },
+    ]
+    elements = elements_a + elements_b
+
+    schema_map = {
+        spec_with_project + 'users': schema_a,
+        spec_with_project + 'scores': schema_b,
+    }
+
+    bq_matchers = [
+        BigqueryFullResultMatcher(
+            project=self.project,
+            query="SELECT id, name FROM %s" % table_a,
+            data=self.parse_expected_data(elements_a)),
+        BigqueryFullResultMatcher(
+            project=self.project,
+            query="SELECT id, score, active FROM %s" % table_b,
+            data=self.parse_expected_data(elements_b)),
+    ]
+
+    def get_destination(record):
+      if 'name' in record:
+        return spec_with_project + 'users'
+      return spec_with_project + 'scores'
+
+    def get_schema_raw(dest, side_map):
+      return side_map[dest]
+
+    get_schema = bigquery.dynamic_schema(
+        get_schema_raw,
+        union_schema="id:INTEGER,name:STRING,score:INTEGER,active:BOOLEAN")
+
+    with beam.Pipeline(argv=self.args) as p:
+      schema_pc = p | "CreateSchema" >> beam.Create([schema_map])
+      _ = (
+          p
+          | "CreateElements" >> beam.Create(elements)
+          | beam.io.WriteToBigQuery(
+              table=get_destination,
+              method=beam.io.WriteToBigQuery.Method.STORAGE_WRITE_API,
+              schema=get_schema,
+              schema_side_inputs=(beam.pvalue.AsSingleton(schema_pc), ),
+              use_at_least_once=False))
+    hamcrest_assert(p, all_of(*bq_matchers))
+

Review Comment:
   Can we also validate the expected schema of the tables that were created after the pipeline ran?



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-4916928579

   > [!WARNING]
   > Gemini encountered an error creating the review. You can try again by commenting `/gemini review`.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5427795265

   ## [Codecov](https://app.codecov.io/gh/apache/beam/pull/39236?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `69.60784%` with `31 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 57.13%. Comparing base ([`524036f`](https://app.codecov.io/gh/apache/beam/commit/524036fb5236fed0f5065c6dc3f45e72402506a8?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b42fda7`](https://app.codecov.io/gh/apache/beam/commit/b42fda7ae882ba4e4d031ccb9368db2d5aa26518?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 134 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/beam/pull/39236?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...sdk/io/gcp/bigquery/TableRowToStorageApiProto.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2FTableRowToStorageApiProto.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L1RhYmxlUm93VG9TdG9yYWdlQXBpUHJvdG8uamF2YQ==) | 59.25% | [5 Missing and 6 partials :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...igQueryStorageWriteApiSchemaTransformProvider.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2Fproviders%2FBigQueryStorageWriteApiSchemaTransformProvider.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L3Byb3ZpZGVycy9CaWdRdWVyeVN0b3JhZ2VXcml0ZUFwaVNjaGVtYVRyYW5zZm9ybVByb3ZpZGVyLmphdmE=) | 41.17% | [8 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...bigquery/StorageApiDynamicDestinationsBeamRow.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2FStorageApiDynamicDestinationsBeamRow.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L1N0b3JhZ2VBcGlEeW5hbWljRGVzdGluYXRpb25zQmVhbVJvdy5qYXZh) | 86.66% | [1 Missing and 3 partials :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...igquery/StorageApiDynamicDestinationsTableRow.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2FStorageApiDynamicDestinationsTableRow.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L1N0b3JhZ2VBcGlEeW5hbWljRGVzdGluYXRpb25zVGFibGVSb3cuamF2YQ==) | 71.42% | [1 Missing and 3 partials :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [.../sdk/io/gcp/bigquery/BeamRowToStorageApiProto.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2FBeamRowToStorageApiProto.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L0JlYW1Sb3dUb1N0b3JhZ2VBcGlQcm90by5qYXZh) | 90.90% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...rg/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&filepath=sdks%2Fjava%2Fio%2Fgoogle-cloud-platform%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fbeam%2Fsdk%2Fio%2Fgcp%2Fbigquery%2FBigQueryIO.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c2Rrcy9qYXZhL2lvL2dvb2dsZS1jbG91ZC1wbGF0Zm9ybS9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvYmVhbS9zZGsvaW8vZ2NwL2JpZ3F1ZXJ5L0JpZ1F1ZXJ5SU8uamF2YQ==) | 66.66% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/beam/pull/39236?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #39236      +/-   ##
   ============================================
   + Coverage     54.94%   57.13%   +2.18%     
   - Complexity     1722     3672    +1950     
   ============================================
     Files          1071     1191     +120     
     Lines        170742   192756   +22014     
     Branches       1262     3856    +2594     
   ============================================
   + Hits          93819   110124   +16305     
   - Misses        74653    79051    +4398     
   - Partials       2270     3581    +1311     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/beam/pull/39236/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [java](https://app.codecov.io/gh/apache/beam/pull/39236/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `72.16% <69.60%> (+4.47%)` | :arrow_up: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/beam/pull/39236?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "ahmedabu98 (via GitHub)" <gi...@apache.org>.
ahmedabu98 commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6150937871

   > the only question is if we want to provide a "dynamic destinations, static schemas" version of this before we implement Variant
   
   Yeah agreed. Are there people asking for this, and is it an urgent ask?


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5269114017

   Thinking about the branching path a little bit, that really only works for cases where you have a static map of schemas known at runtime and don't have side inputs or callable schema determination, since you can't change the shape of the DAG during runtime. It does explode the number of xlang calls too, since you're instantiating a cross-language transform per-schema.
   
   The point about create-on-write tables inheriting the union schema is right though, that is now documented and test cases use pre-existing tables now.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5035498279

   @gemini-code-assist review


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on code in PR #39236:
URL: https://github.com/apache/beam/pull/39236#discussion_r3960207193


##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java:
##########
@@ -4011,11 +4011,13 @@ private <DestinationT> WriteResult expandTyped(
         // TODO: If the user provided a schema, we should use that. There are things that can be
         // specified in a
         // BQ schema that don't have exact matches in a Beam schema (e.g. GEOGRAPHY types).
-        TableSchema tableSchema = BigQueryUtils.toTableSchema(input.getSchema());
-        dynamicDestinations =
-            new ConstantSchemaDestinations<>(
-                dynamicDestinations,
-                StaticValueProvider.of(BigQueryHelpers.toJsonString(tableSchema)));
+        if (!hasSchema) {

Review Comment:
   The definition of hasSchema conflates "the user supplied a DynamicDestinations" with "the user supplied a schema". The javadoc of useBeamSchema promises the BQ schema is inferred from the input schema.
   
   This change means that user supplied schema overrules the inferred schema, which could potentially be a breaking change if someone just passed an invalid schema while silently relying on input schema?
   
   Also I think this will fail pipelines that have DynamicDestination + getSchema returns null?
   
   ```
   @DefaultSchema(JavaFieldSchema.class)
   class Event { String type; String name; int number; }
   
   p.apply(Create.of(new Event("click", "a", 1), new Event("view", "b", 2)))
    .apply(BigQueryIO.<Event>write()
        .to(new DynamicDestinations<Event, String>() {
          public String getDestination(ValueInSingleWindow<Event> e) {
            return "proj:ds.events_" + e.getValue().type;
          }
          public TableDestination getTable(String dest) {
            return new TableDestination(dest, null);
          }
          public @Nullable TableSchema getSchema(String dest) {
            return null;   // inferred from the Beam schema, per useBeamSchema()
          }
        })
        .useBeamSchema()
        .withMethod(STORAGE_WRITE_API)
        .withCreateDisposition(CREATE_IF_NEEDED));
   ```
   
   because
   
   https://github.com/jrmccluskey/beam/blob/3353e1ba3380ab65ac9457556f44bd66ceb508db/sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.java#L3988-L3991
   



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/StorageApiDynamicDestinationsTableRow.java:
##########
@@ -94,8 +93,29 @@ public MessageConverter<T> getMessageConverter(
           }
         };
 
+    TableSchema destSchema = getSchema(destination);

Review Comment:
   Everything here runs for every Storage Write API use.
   
   Can we scope these changes to only the portable provider?
   
   The declared schema is no longer authoritative for the proto descriptor. If there was a mismatch writing to BQ would raise an error. 
   
   Is this a regression for users who relied on the declared schema being authoritative and on disagreement being loud?
   
   Some potentially changed behaviors
   | Case | Master | Branch | Verdict |
   |---|---|---|---|
   | D equals T, R has an extra key with a null value | Per-row failure to failed rows | Silently dropped, row written | Changed by the null skip alone. The documented default "unknown values are errors" no longer holds for nulls |
   | D wider than T, R's extra column is null | Stream-level INVALID_ARGUMENT, job stalls or fails, zero rows | T substituted, column dropped, row written, job succeeds | Changed |
   | D wider than T, R's extra column is non-null | Same stream-level failure | T substituted, per-row failure to failed rows, job succeeds | Changed |
   | D wider than T, user set `ignoreUnknownValues()` | Still the stream-level failure, since that option only governs row versus descriptor | T substituted, extra column dropped for every row | Changed, and arguably what that user wanted |
   | D wider than T, then someone adds the column to T while the job runs | Next append succeeds, the job heals on its own | Cached T is never refreshed in strict mode, so the column keeps being dropped or failed until the workers restart | Changed, an operability regression |
   
   D = declared schema, T = existing table schema, R = a row.
   
   D = declared schema, T = existing table schema, R = a row.
   



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "claudevdm (via GitHub)" <gi...@apache.org>.
claudevdm commented on code in PR #39236:
URL: https://github.com/apache/beam/pull/39236#discussion_r4219754055


##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -2883,25 +3089,175 @@ def __enter__(self):
     def __exit__(self, *args):
       pass
 
+  class _ConvertDynamicRowDoFn(DoFn):
+    def __init__(
+        self,
+        schema,
+        union_field_names,
+        create_disposition=BigQueryDisposition.CREATE_IF_NEEDED,
+        write_disposition=BigQueryDisposition.WRITE_APPEND,
+        additional_bq_parameters=None,
+        test_client=None):
+      self.schema = schema
+      self.union_field_names = union_field_names
+      self.create_disposition = create_disposition
+      self.write_disposition = write_disposition
+      self.additional_bq_parameters = additional_bq_parameters
+      self.test_client = test_client
+      self.bigquery_wrapper = None
+
+    def start_bundle(self):
+      if self.create_disposition == BigQueryDisposition.CREATE_IF_NEEDED:
+        if self.test_client:
+          self.bigquery_wrapper = bigquery_tools.BigQueryWrapper(
+              client=self.test_client)
+        else:
+          try:
+            self.bigquery_wrapper = bigquery_tools.BigQueryWrapper()
+          except Exception:
+            self.bigquery_wrapper = None
+
+    def _create_table_if_needed(self, dest, record_schema):
+      if self.create_disposition != BigQueryDisposition.CREATE_IF_NEEDED:
+        return
+      try:
+        table_ref = bigquery_tools.parse_table_reference(dest)
+      except ValueError:
+        return
+      if not table_ref.datasetId or not table_ref.tableId:
+        return
+
+      if self.bigquery_wrapper is None:
+        if self.test_client:
+          self.bigquery_wrapper = bigquery_tools.BigQueryWrapper(
+              client=self.test_client)
+        else:
+          try:
+            self.bigquery_wrapper = bigquery_tools.BigQueryWrapper()
+          except Exception:
+            return
+
+      project_id = (
+          table_ref.projectId or self.bigquery_wrapper._get_project_id())
+      str_table_ref = '%s:%s.%s' % (
+          project_id, table_ref.datasetId, table_ref.tableId)
+      if str_table_ref in _KNOWN_TABLES or dest in _KNOWN_TABLES:
+        return
+
+      table_schema = bigquery_tools.get_bq_tableschema(record_schema)
+      self.bigquery_wrapper.get_or_create_table(
+          project_id=project_id,
+          dataset_id=table_ref.datasetId,
+          table_id=table_ref.tableId,
+          schema=table_schema,
+          create_disposition=self.create_disposition,
+          write_disposition=self.write_disposition,

Review Comment:
   This passes the user's write disposition to `get_or_create_table`. For WRITE_TRUNCATE that helper deletes the table, creates it again and sleeps 150 seconds, and here it runs inside `process`.
   
   `_KNOWN_TABLES` is per process, so every worker process does this the first time it sees a row for a table.
   
   Can we always pass WRITE_APPEND here?
   



##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -2883,25 +3089,175 @@ def __enter__(self):
     def __exit__(self, *args):
       pass
 
+  class _ConvertDynamicRowDoFn(DoFn):
+    def __init__(
+        self,
+        schema,
+        union_field_names,
+        create_disposition=BigQueryDisposition.CREATE_IF_NEEDED,
+        write_disposition=BigQueryDisposition.WRITE_APPEND,
+        additional_bq_parameters=None,
+        test_client=None):
+      self.schema = schema
+      self.union_field_names = union_field_names
+      self.create_disposition = create_disposition
+      self.write_disposition = write_disposition
+      self.additional_bq_parameters = additional_bq_parameters
+      self.test_client = test_client
+      self.bigquery_wrapper = None
+
+    def start_bundle(self):
+      if self.create_disposition == BigQueryDisposition.CREATE_IF_NEEDED:
+        if self.test_client:
+          self.bigquery_wrapper = bigquery_tools.BigQueryWrapper(
+              client=self.test_client)
+        else:
+          try:
+            self.bigquery_wrapper = bigquery_tools.BigQueryWrapper()
+          except Exception:
+            self.bigquery_wrapper = None
+
+    def _create_table_if_needed(self, dest, record_schema):
+      if self.create_disposition != BigQueryDisposition.CREATE_IF_NEEDED:
+        return
+      try:
+        table_ref = bigquery_tools.parse_table_reference(dest)
+      except ValueError:
+        return
+      if not table_ref.datasetId or not table_ref.tableId:
+        return
+
+      if self.bigquery_wrapper is None:
+        if self.test_client:
+          self.bigquery_wrapper = bigquery_tools.BigQueryWrapper(
+              client=self.test_client)
+        else:
+          try:
+            self.bigquery_wrapper = bigquery_tools.BigQueryWrapper()
+          except Exception:
+            return
+
+      project_id = (
+          table_ref.projectId or self.bigquery_wrapper._get_project_id())
+      str_table_ref = '%s:%s.%s' % (
+          project_id, table_ref.datasetId, table_ref.tableId)
+      if str_table_ref in _KNOWN_TABLES or dest in _KNOWN_TABLES:
+        return
+
+      table_schema = bigquery_tools.get_bq_tableschema(record_schema)
+      self.bigquery_wrapper.get_or_create_table(
+          project_id=project_id,
+          dataset_id=table_ref.datasetId,
+          table_id=table_ref.tableId,
+          schema=table_schema,
+          create_disposition=self.create_disposition,
+          write_disposition=self.write_disposition,
+          additional_create_parameters=self.additional_bq_parameters)
+      _KNOWN_TABLES.add(str_table_ref)
+      _KNOWN_TABLES.add(dest)
+
+    def process(self, row, *schema_side_inputs):
+      dest, dict_row = row[0], row[1]
+      record_schema = self.schema(dest, *schema_side_inputs)
+      self._create_table_if_needed(dest, record_schema)
+
+      if record_schema is None or record_schema == SCHEMA_AUTODETECT:
+        schema_json = ''
+      else:
+        schema_dict = bigquery_tools.get_dict_table_schema(record_schema)
+        schema_json = json.dumps(schema_dict)
+
+      record_row = bigquery_tools.beam_row_from_dict(dict_row, record_schema)
+      if self.union_field_names:
+        record_dict = record_row._asdict()
+        record_row = beam.Row(
+            **{
+                name: record_dict.get(name, None)
+                for name in self.union_field_names
+            })
+      yield beam.Row(
+          **{
+              StorageWriteToBigQuery.DESTINATION: dest,
+              StorageWriteToBigQuery.SCHEMA: schema_json,

Review Comment:
   A full json schema seems like a lot of byte overhead per row. Should we consider proto encoding or something to make this more efficient for shuffle (streaming exactly once)? 



##########
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/providers/PortableBigQueryDestinations.java:
##########
@@ -23,29 +23,47 @@
 
 import com.google.api.services.bigquery.model.Clustering;
 import com.google.api.services.bigquery.model.TableConstraints;
+import com.google.api.services.bigquery.model.TableFieldSchema;
 import com.google.api.services.bigquery.model.TableRow;
 import com.google.api.services.bigquery.model.TableSchema;
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
 import org.apache.avro.generic.GenericRecord;
 import org.apache.beam.sdk.annotations.Internal;
+import org.apache.beam.sdk.coders.Coder;
+import org.apache.beam.sdk.coders.KvCoder;
+import org.apache.beam.sdk.coders.NullableCoder;
+import org.apache.beam.sdk.coders.StringUtf8Coder;
 import org.apache.beam.sdk.extensions.avro.schemas.utils.AvroUtils;
 import org.apache.beam.sdk.io.gcp.bigquery.AvroWriteRequest;
+import org.apache.beam.sdk.io.gcp.bigquery.BigQueryHelpers;
 import org.apache.beam.sdk.io.gcp.bigquery.BigQueryUtils;
 import org.apache.beam.sdk.io.gcp.bigquery.DynamicDestinations;
 import org.apache.beam.sdk.io.gcp.bigquery.TableDestination;
 import org.apache.beam.sdk.schemas.Schema;
 import org.apache.beam.sdk.transforms.SerializableFunction;
 import org.apache.beam.sdk.util.RowFilter;
 import org.apache.beam.sdk.util.RowStringInterpolator;
+import org.apache.beam.sdk.values.KV;
 import org.apache.beam.sdk.values.Row;
 import org.apache.beam.sdk.values.ValueInSingleWindow;
+import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.annotations.VisibleForTesting;
 import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
 import org.checkerframework.checker.nullness.qual.Nullable;
 
 @Internal
-public class PortableBigQueryDestinations extends DynamicDestinations<Row, String> {
+public class PortableBigQueryDestinations
+    extends DynamicDestinations<Row, KV<String, @Nullable String>> {

Review Comment:
   Is this a breaking change for streaming compatibility? 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5038756467

   Assigning reviewers:
   
   R: @shunping for label python.
   
   
   Note: If you would like to opt out of this review, comment `assign to next reviewer`.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on code in PR #39236:
URL: https://github.com/apache/beam/pull/39236#discussion_r3759338936


##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -197,6 +197,43 @@ def compute_table_name(row):
 a tuple of PCollectionViews to be passed to the schema callable (much like
 the `table_side_inputs` parameter).
 
+Dynamic Schemas with Storage Write API
+--------------------------------------
+When writing to dynamic destinations with `method=STORAGE_WRITE_API`, a union schema
+containing all fields across destination tables is required at the PCollection level

Review Comment:
   Each destination table only implements its own schema, it does not have to implement the full union schema. The union schema is (unfortunately) necessary in this setup because the storage write API calls are cross-language and a coder has to be defined to send elements to the Java SDK that actually does the writes. 



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "ahmedabu98 (via GitHub)" <gi...@apache.org>.
ahmedabu98 commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6134009021

   I'm a little iffy about this approach. It requires the input PCollection schema to be the full union of all destination table schemas. And the input schema is still fixed, so can't meet the need of new tables containing new columns, or existing table schema updates.
   
   Also tables with identical column names will need to agree on their types and modes (e.g. table1 has colA as a nullable INT32 but table2 has colA as an array of Strings)
   
   I think a more robust long term solution would need a semi-structured type like Variant so rows can include only what they need (see https://github.com/apache/beam/issues/38251)


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-6153504373

   > > the only question is if we want to provide a "dynamic destinations, static schemas" version of this before we implement Variant
   > 
   > Yeah agreed. Are there people asking for this, and is it an urgent ask?
   
   This is a customer ask, but I would not call it urgent (last actual ask on this was back in July.) I am leaning towards adding the static schema version of this as a middle ground with documentation around the limitations and future work planned.


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5117991018

   Reminder, please take a look at this pr: @shunping 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5587655214

   Did you have time to check this, @claudevdm? 


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5138100764

   r: @claudevdm 
   
   Could help to review this since you are more familiar with BigQueryIO? Thanks!
   
   


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [WIP] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #39236:
URL: https://github.com/apache/beam/pull/39236#discussion_r3623188482


##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -2797,24 +2958,84 @@ def __exit__(self, *args):
       pass
 
   class ConvertToBeamRows(PTransform):
-    def __init__(self, schema, dynamic_destinations, type_overrides=None):
+    def __init__(
+        self,
+        schema,
+        dynamic_destinations,
+        type_overrides=None,
+        schema_side_inputs=None):
       self.schema = schema
       self.dynamic_destinations = dynamic_destinations
       self.type_overrides = type_overrides
+      self.schema_side_inputs = schema_side_inputs or ()
+
+    def _get_record_type_hint(self):
+      if callable(self.schema):
+        schema_hint = (
+            getattr(self.schema, '_union_schema', None) or
+            getattr(self.schema, '_table_schema', None) or
+            getattr(self.schema, '_beam_schema', None) or
+            getattr(self.schema, '_schema_hint', None) or
+            getattr(self.schema, '_output_types', None) or
+            getattr(self.schema, 'table_schema', None) or
+            getattr(self.schema, 'schema', None))
+        if schema_hint is not None:
+          if isinstance(
+              schema_hint,
+              (bigquery.TableSchema, bigquery.TableFieldSchema, str, dict)):

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   Using `bigquery.TableSchema` and `bigquery.TableFieldSchema` inside `bigquery.py` will raise a `NameError` at runtime. Please reference `TableSchema` and `TableFieldSchema` directly.
   
   ```suggestion
                 (TableSchema, TableFieldSchema, str, dict)):
   ```



##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -1956,6 +1993,120 @@ def _restore_table_ref(sharded_table_ref_elems_kv):
 SCHEMA_AUTODETECT = 'SCHEMA_AUTODETECT'
 
 
+def dynamic_schema(schema_fn_or_map, union_schema=None):
+  """Helper to construct a dynamic schema callable with a union schema hint.
+
+  When using the BigQuery Storage Write API (`method=STORAGE_WRITE_API`) with
+  dynamic destinations, the cross-language transform requires a PCollection-level
+  union schema containing all fields across all target tables for protobuf
+  serialization and type inference.
+
+  This helper provides the recommended best practice for constructing dynamic
+  schemas:
+
+  1. **Dictionary Map**: If destination table schemas are provided as a dictionary
+     mapping table names/specs to schemas (str, dict, or TableSchema), this helper
+     automatically merges all fields into a single union schema.
+  2. **Callable**: If a callable function is used, this helper attaches the provided
+     `union_schema` to the callable as a schema hint (`_union_schema`).
+
+  Example using a dictionary map (union schema is auto-inferred)::
+
+      schema_map = {
+          'project:dataset.users': 'id:INTEGER,name:STRING',
+          'project:dataset.scores': 'id:INTEGER,score:INTEGER,active:BOOLEAN'
+      }
+
+      def get_destination(record):
+        if 'name' in record:
+          return 'project:dataset.users'
+        return 'project:dataset.scores'
+
+      schema_callable = dynamic_schema(schema_map)
+
+      elements | WriteToBigQuery(
+          table=get_destination,
+          method=WriteToBigQuery.Method.STORAGE_WRITE_API,
+          schema=schema_callable)
+
+  Example using a callable with explicit union schema::
+
+      def get_schema(destination, schema_side_input):
+        return schema_side_input[destination]
+
+      schema_callable = dynamic_schema(
+          get_schema,
+          union_schema='id:INTEGER,name:STRING,score:INTEGER,active:BOOLEAN')
+
+      elements | WriteToBigQuery(
+          table=get_destination,
+          method=WriteToBigQuery.Method.STORAGE_WRITE_API,
+          schema=schema_callable,
+          schema_side_inputs=(schema_side_input,))
+
+  Args:
+    schema_fn_or_map: A callable `(destination, *side_inputs) -> schema`
+      or a dictionary mapping destination strings to schemas (str, dict, or
+      TableSchema).
+    union_schema: (Optional) The union schema containing all fields across
+      target tables. Can be a string, dict, or TableSchema object. Required if
+      `schema_fn_or_map` is a callable.
+
+  Returns:
+    A callable with the attached `_union_schema` attribute for Storage Write API.
+  """
+  if isinstance(schema_fn_or_map, dict):
+    if union_schema is None:
+      bq_schemas = [
+          bigquery_tools.get_bq_tableschema(s)
+          for s in schema_fn_or_map.values()
+      ]
+
+      def _merge_fields(field_a, field_b):
+        if field_a.type != field_b.type:
+          raise ValueError(
+              f"Conflicting types for field '{field_a.name}': "
+              f"{field_a.type} vs {field_b.type}")
+        if field_a.type in ('RECORD', 'STRUCT'):
+          merged_subfields = {}
+          for f in (field_a.fields or []):
+            merged_subfields[f.name] = f
+          for f in (field_b.fields or []):
+            if f.name in merged_subfields:
+              merged_subfields[f.name] = _merge_fields(
+                  merged_subfields[f.name], f)
+            else:
+              merged_subfields[f.name] = f
+          field_a.fields = list(merged_subfields.values())
+        return field_a
+
+      merged_fields = {}
+      for schema in bq_schemas:
+        for field in schema.fields:
+          name = field.name
+          if name in merged_fields:
+            merged_fields[name] = _merge_fields(merged_fields[name], field)
+          else:
+            merged_fields[name] = field
+      union_schema = bigquery.TableSchema(fields=list(merged_fields.values()))

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   Using `bigquery.TableSchema` inside `bigquery.py` will raise a `NameError` at runtime because `bigquery` is the name of the module itself and is not defined in the global namespace of this file. Please reference `TableSchema` directly.
   
   ```suggestion
         union_schema = TableSchema(fields=list(merged_fields.values()))
   ```



##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -1956,6 +1993,120 @@ def _restore_table_ref(sharded_table_ref_elems_kv):
 SCHEMA_AUTODETECT = 'SCHEMA_AUTODETECT'
 
 
+def dynamic_schema(schema_fn_or_map, union_schema=None):
+  """Helper to construct a dynamic schema callable with a union schema hint.
+
+  When using the BigQuery Storage Write API (`method=STORAGE_WRITE_API`) with
+  dynamic destinations, the cross-language transform requires a PCollection-level
+  union schema containing all fields across all target tables for protobuf
+  serialization and type inference.
+
+  This helper provides the recommended best practice for constructing dynamic
+  schemas:
+
+  1. **Dictionary Map**: If destination table schemas are provided as a dictionary
+     mapping table names/specs to schemas (str, dict, or TableSchema), this helper
+     automatically merges all fields into a single union schema.
+  2. **Callable**: If a callable function is used, this helper attaches the provided
+     `union_schema` to the callable as a schema hint (`_union_schema`).
+
+  Example using a dictionary map (union schema is auto-inferred)::
+
+      schema_map = {
+          'project:dataset.users': 'id:INTEGER,name:STRING',
+          'project:dataset.scores': 'id:INTEGER,score:INTEGER,active:BOOLEAN'
+      }
+
+      def get_destination(record):
+        if 'name' in record:
+          return 'project:dataset.users'
+        return 'project:dataset.scores'
+
+      schema_callable = dynamic_schema(schema_map)
+
+      elements | WriteToBigQuery(
+          table=get_destination,
+          method=WriteToBigQuery.Method.STORAGE_WRITE_API,
+          schema=schema_callable)
+
+  Example using a callable with explicit union schema::
+
+      def get_schema(destination, schema_side_input):
+        return schema_side_input[destination]
+
+      schema_callable = dynamic_schema(
+          get_schema,
+          union_schema='id:INTEGER,name:STRING,score:INTEGER,active:BOOLEAN')
+
+      elements | WriteToBigQuery(
+          table=get_destination,
+          method=WriteToBigQuery.Method.STORAGE_WRITE_API,
+          schema=schema_callable,
+          schema_side_inputs=(schema_side_input,))
+
+  Args:
+    schema_fn_or_map: A callable `(destination, *side_inputs) -> schema`
+      or a dictionary mapping destination strings to schemas (str, dict, or
+      TableSchema).
+    union_schema: (Optional) The union schema containing all fields across
+      target tables. Can be a string, dict, or TableSchema object. Required if
+      `schema_fn_or_map` is a callable.
+
+  Returns:
+    A callable with the attached `_union_schema` attribute for Storage Write API.
+  """
+  if isinstance(schema_fn_or_map, dict):
+    if union_schema is None:
+      bq_schemas = [
+          bigquery_tools.get_bq_tableschema(s)
+          for s in schema_fn_or_map.values()
+      ]

Review Comment:
   ![medium](https://www.gstatic.com/codereviewagent/medium-priority.svg)
   
   The `_merge_fields` helper mutates the fields of the input schemas in-place. If the user passes existing `TableSchema` objects in `schema_fn_or_map`, `get_bq_tableschema` returns them directly, meaning this helper will silently mutate the user's original schema objects. To prevent unexpected side effects, please deepcopy the schemas before merging them.
   
   ```suggestion
         import copy
         bq_schemas = [
             copy.deepcopy(bigquery_tools.get_bq_tableschema(s))
             for s in schema_fn_or_map.values()
         ]
   ```



##########
sdks/python/apache_beam/io/gcp/bigquery.py:
##########
@@ -2797,24 +2958,84 @@ def __exit__(self, *args):
       pass
 
   class ConvertToBeamRows(PTransform):
-    def __init__(self, schema, dynamic_destinations, type_overrides=None):
+    def __init__(
+        self,
+        schema,
+        dynamic_destinations,
+        type_overrides=None,
+        schema_side_inputs=None):
       self.schema = schema
       self.dynamic_destinations = dynamic_destinations
       self.type_overrides = type_overrides
+      self.schema_side_inputs = schema_side_inputs or ()
+
+    def _get_record_type_hint(self):
+      if callable(self.schema):
+        schema_hint = (
+            getattr(self.schema, '_union_schema', None) or
+            getattr(self.schema, '_table_schema', None) or
+            getattr(self.schema, '_beam_schema', None) or
+            getattr(self.schema, '_schema_hint', None) or
+            getattr(self.schema, '_output_types', None) or
+            getattr(self.schema, 'table_schema', None) or
+            getattr(self.schema, 'schema', None))
+        if schema_hint is not None:
+          if isinstance(
+              schema_hint,
+              (bigquery.TableSchema, bigquery.TableFieldSchema, str, dict)):
+            row_type_hints = bigquery_tools.get_beam_typehints_from_tableschema(
+                schema_hint, self.type_overrides)
+            return RowTypeConstraint.from_fields(row_type_hints)
+          elif isinstance(schema_hint, RowTypeConstraint):
+            return schema_hint
+        return RowTypeConstraint.from_fields([])
+      else:
+        row_type_hints = bigquery_tools.get_beam_typehints_from_tableschema(
+            self.schema, self.type_overrides)
+        return RowTypeConstraint.from_fields(row_type_hints)
 
     def expand(self, input_dicts):
       if self.dynamic_destinations:
-        return (
-            input_dicts
-            | "Convert dict to Beam Row" >> beam.Map(
-                lambda row, schema=DoFn.SetupContextParam(
-                    StorageWriteToBigQuery.ConvertToBeamRowsSetupSchema, args=
-                    [self.schema]): beam.Row(
-                        **{
-                            StorageWriteToBigQuery.DESTINATION: row[0],
-                            StorageWriteToBigQuery.RECORD: bigquery_tools.
-                            beam_row_from_dict(row[1], schema)
-                        })))
+        if callable(self.schema):
+          record_hint = self._get_record_type_hint()
+          union_field_names = [
+              name for name, _ in getattr(record_hint, '_fields', ())
+          ]
+
+          def convert_dynamic_row(row, *schema_side_inputs):
+            dest, dict_row = row[0], row[1]
+            record_schema = self.schema(dest, *schema_side_inputs)
+            record_row = bigquery_tools.beam_row_from_dict(
+                dict_row, record_schema)
+            if union_field_names:
+              record_dict = record_row._asdict()
+              record_row = beam.Row(
+                  **{
+                      name: record_dict.get(name, None)
+                      for name in union_field_names
+                  })
+            return beam.Row(
+                **{
+                    StorageWriteToBigQuery.DESTINATION: dest,
+                    StorageWriteToBigQuery.RECORD: record_row
+                })

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   Constructing a new `beam.Row` using `beam.Row(**...)` with dynamic keyword arguments causes Beam to infer the schema on the fly. For fields that are `None`, their types will be inferred as `NoneType` (or `Any`), which means different rows will have different inferred schemas. This will cause serialization/encoding errors (e.g., `CoderException`) at the cross-language boundary because the `RowCoder` expects a consistent schema matching the union schema.
   
   Additionally, converting to a dict, performing a dict comprehension, and instantiating a new `beam.Row` for every single element introduces significant CPU overhead.
   
   Instead, you can use `bigquery_tools.beam_row_from_dict` with the pre-resolved `union_bq_schema` to safely and efficiently pad/convert the row to the union schema.
   
   ```python
             union_schema = getattr(self.schema, '_union_schema', None)
             union_bq_schema = (
                 bigquery_tools.get_bq_tableschema(union_schema)
                 if union_schema else None)
   
             def convert_dynamic_row(row, *schema_side_inputs):
               dest, dict_row = row[0], row[1]
               record_schema = self.schema(dest, *schema_side_inputs)
               record_row = bigquery_tools.beam_row_from_dict(
                   dict_row, record_schema)
               if union_bq_schema:
                 record_row = bigquery_tools.beam_row_from_dict(
                     record_row._asdict(), union_bq_schema)
               return beam.Row(
                   **{
                       StorageWriteToBigQuery.DESTINATION: dest,
                       StorageWriteToBigQuery.RECORD: record_row
                   })
   ```



-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add Dynamic Schema support to StorageWriteToBigQuery [beam]

Posted by "jrmccluskey (via GitHub)" <gi...@apache.org>.
jrmccluskey commented on PR #39236:
URL: https://github.com/apache/beam/pull/39236#issuecomment-5441680392

   @claudevdm I __think__ this works now, PTAL


-- 
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: github-unsubscribe@beam.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org