Skip to content

[Gemini] Migrate Python BigQuery off of apitools client#39087

Draft
jrmccluskey wants to merge 36 commits into
apache:masterfrom
jrmccluskey:bqMigration
Draft

[Gemini] Migrate Python BigQuery off of apitools client#39087
jrmccluskey wants to merge 36 commits into
apache:masterfrom
jrmccluskey:bqMigration

Conversation

@jrmccluskey

Copy link
Copy Markdown
Contributor

Migrates the BQ client to the supported Python library and off of the deprecated apitools client.

DO NOT MERGE - needs internal testing


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.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit 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
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@jrmccluskey

Copy link
Copy Markdown
Contributor Author

@gemini-code-assist review

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request migrates the Apache Beam Python SDK's BigQuery integration from the legacy apitools client to the official google-cloud-bigquery library. The feedback highlights several critical issues and regressions introduced during this migration. Specifically, manual base64 encoding of bytes should be removed as the new client handles this natively, and broad exception-swallowing during table and dataset deletions should be avoided to prevent hiding critical errors. Additionally, several redundant try-except blocks, a leftover debug print statement, and an ad-hoc MockJob implementation on conflict should be cleaned up.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread sdks/python/apache_beam/io/gcp/big_query_query_to_table_it_test.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_file_loads.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
Comment thread sdks/python/apache_beam/io/gcp/bigquery_tools.py Outdated
@jrmccluskey

Copy link
Copy Markdown
Contributor Author

@gemini-code-assist review

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request migrates the Apache Beam Python SDK's BigQuery integration from the legacy apitools client to the modern google-cloud-bigquery library. The review feedback highlights several critical runtime issues introduced by this migration, including potential AttributeErrors due to mixed usage of camelCase and snake_case attributes on job and table references, potential ImportErrors from inline imports of google.cloud.bigquery classes where fallback classes should be used, and a NameError in tests due to an unbound import. Addressing these issues by standardizing on google-cloud-bigquery types and robustly handling dictionary schemas will ensure a stable migration.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines 479 to 486
return [
FieldSchema(cls._convert_to_tuple(x.fields), x.mode, x.name, x.type)
FieldSchema(
cls._convert_to_tuple(x.fields),
x.mode,
x.name,
getattr(x, "field_type", getattr(x, "type", None)))
for x in table_field_schemas
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

When table_schema is a dictionary, table_field_schemas is a list of dictionaries. Attempting to access attributes like x.fields, x.mode, x.name on x will raise an AttributeError because x is a dictionary. We should robustly handle both SchemaField objects and dict objects.

Suggested change
return [
FieldSchema(cls._convert_to_tuple(x.fields), x.mode, x.name, x.type)
FieldSchema(
cls._convert_to_tuple(x.fields),
x.mode,
x.name,
getattr(x, "field_type", getattr(x, "type", None)))
for x in table_field_schemas
]
res = []
for x in table_field_schemas:
if isinstance(x, dict):
fields = x.get('fields', [])
mode = x.get('mode', 'NULLABLE')
name = x.get('name')
field_type = x.get('type')
else:
fields = getattr(x, 'fields', [])
mode = getattr(x, 'mode', 'NULLABLE')
name = getattr(x, 'name')
field_type = getattr(x, 'field_type', getattr(x, 'type', None))
res.append(FieldSchema(cls._convert_to_tuple(fields), mode, name, field_type))
return res

Comment on lines +684 to +687
if state == 'DONE' and error_result:
raise RuntimeError(
'BigQuery job {} failed. Error Result: {}'.format(
job_reference.jobId, job.status.errorResult))
elif job.status.state == 'DONE':
job_reference.jobId, error_result))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The job_reference object can be a google.cloud.bigquery.job instance (such as LoadJob or QueryJob) which has job_id but not jobId. Accessing job_reference.jobId will raise an AttributeError at runtime. Use the local variable job_id instead, which was safely extracted using getattr above.

Suggested change
if state == 'DONE' and error_result:
raise RuntimeError(
'BigQuery job {} failed. Error Result: {}'.format(
job_reference.jobId, job.status.errorResult))
elif job.status.state == 'DONE':
job_reference.jobId, error_result))
if state == 'DONE' and error_result:
raise RuntimeError(
'BigQuery job {} failed. Error Result: {}'.format(
job_id, error_result))

Comment on lines +1076 to +1087
try:
job = self.client.extract_table(
source=table_reference,
destination_uris=destination,
job_id=job_id,
project=job_project,
job_config=job_config)
return job
except google_api_core_exceptions.Conflict as exn:
_LOGGER.info("BigQuery job %s already exists", job_id)
job_location = self._parse_location_from_exc(exn.message, job_id)
return self.get_job(job_project, job_id, job_location)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To maintain consistency with other job-starting methods in BigQueryWrapper (such as _insert_load_job, _insert_copy_job, and _start_query_job), perform_extract_job should return a BeamJobReference instead of an ExtractJob or Job object. Callers expecting a job reference with projectId and jobId attributes will fail with AttributeError if they receive an ExtractJob or Job object (which only have project and job_id).

    try:
      job = self.client.extract_table(
          source=table_reference,
          destination_uris=destination,
          job_id=job_id,
          project=job_project,
          job_config=job_config)
      return BeamJobReference(
          projectId=job.project, jobId=job.job_id, location=job.location)
    except google_api_core_exceptions.Conflict as exn:
      _LOGGER.info("BigQuery job %s already exists", job_id)
      job_location = self._parse_location_from_exc(exn.message, job_id)
      return BeamJobReference(
          projectId=job_project, jobId=job_id, location=job_location)

Comment on lines 453 to 456
def _get_temp_dataset(self):
if self.temp_table_ref:
return self.temp_table_ref.datasetId
return self.temp_table_ref.dataset_id
return BigQueryWrapper.TEMP_DATASET + self._temporary_table_suffix

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If self.temp_table_ref is an older apitools TableReference or a mock object that only has datasetId (camelCase), accessing self.temp_table_ref.dataset_id will raise an AttributeError. Since self.temp_dataset_id is already safely initialized in __init__ using getattr to handle both datasetId and dataset_id, _get_temp_dataset should simply return self.temp_dataset_id.

Suggested change
def _get_temp_dataset(self):
if self.temp_table_ref:
return self.temp_table_ref.datasetId
return self.temp_table_ref.dataset_id
return BigQueryWrapper.TEMP_DATASET + self._temporary_table_suffix
def _get_temp_dataset(self):
if self.temp_dataset_id:
return self.temp_dataset_id
return BigQueryWrapper.TEMP_DATASET + self._temporary_table_suffix

Comment on lines +400 to +407
if table_reference.project is None or table_reference.project == bigquery_tools.FALLBACK_PROJECT:
from google.cloud.bigquery import DatasetReference
from google.cloud.bigquery import TableReference
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
table_reference = TableReference(
DatasetReference(new_project, table_reference.dataset_id),
table_reference.table_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid inline imports of DatasetReference and TableReference from google.cloud.bigquery inside process. This can raise ImportError if google-cloud-bigquery is not installed, and is redundant because bigquery_tools already exports TableReference and DatasetReference safely with fallback dummy classes.

    if table_reference.project is None or table_reference.project == bigquery_tools.FALLBACK_PROJECT:
      new_project = vp.RuntimeValueProvider.get_value(
          'project', str, '') or self.project
      table_reference = bigquery_tools.TableReference(
          bigquery_tools.DatasetReference(new_project, table_reference.dataset_id),
          table_reference.table_id)

Comment on lines +545 to +564
if copy_to_reference.project is None or copy_to_reference.project == bigquery_tools.FALLBACK_PROJECT:
from google.cloud.bigquery import DatasetReference
from google.cloud.bigquery import TableReference
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
copy_to_reference = TableReference(
DatasetReference(new_project, copy_to_reference.dataset_id),
copy_to_reference.table_id)

copy_from_reference = bigquery_tools.parse_table_reference(destination)
copy_from_reference.tableId = job_reference.jobId
if copy_from_reference.projectId is None:
copy_from_reference.projectId = vp.RuntimeValueProvider.get_value(
new_table_id = job_reference.jobId
new_project = copy_from_reference.project
if new_project is None or new_project == bigquery_tools.FALLBACK_PROJECT:
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
from google.cloud.bigquery import DatasetReference
from google.cloud.bigquery import TableReference
copy_from_reference = TableReference(
DatasetReference(new_project, copy_from_reference.dataset_id),
new_table_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid inline imports of DatasetReference and TableReference from google.cloud.bigquery inside process_one. This can raise ImportError if google-cloud-bigquery is not installed, and is redundant because bigquery_tools already exports TableReference and DatasetReference safely with fallback dummy classes.

Suggested change
if copy_to_reference.project is None or copy_to_reference.project == bigquery_tools.FALLBACK_PROJECT:
from google.cloud.bigquery import DatasetReference
from google.cloud.bigquery import TableReference
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
copy_to_reference = TableReference(
DatasetReference(new_project, copy_to_reference.dataset_id),
copy_to_reference.table_id)
copy_from_reference = bigquery_tools.parse_table_reference(destination)
copy_from_reference.tableId = job_reference.jobId
if copy_from_reference.projectId is None:
copy_from_reference.projectId = vp.RuntimeValueProvider.get_value(
new_table_id = job_reference.jobId
new_project = copy_from_reference.project
if new_project is None or new_project == bigquery_tools.FALLBACK_PROJECT:
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
from google.cloud.bigquery import DatasetReference
from google.cloud.bigquery import TableReference
copy_from_reference = TableReference(
DatasetReference(new_project, copy_from_reference.dataset_id),
new_table_id)
if copy_to_reference.project is None or copy_to_reference.project == bigquery_tools.FALLBACK_PROJECT:
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
copy_to_reference = bigquery_tools.TableReference(
bigquery_tools.DatasetReference(new_project, copy_to_reference.dataset_id),
copy_to_reference.table_id)
copy_from_reference = bigquery_tools.parse_table_reference(destination)
new_table_id = job_reference.jobId
new_project = copy_from_reference.project
if new_project is None or new_project == bigquery_tools.FALLBACK_PROJECT:
new_project = vp.RuntimeValueProvider.get_value(
'project', str, '') or self.project
copy_from_reference = bigquery_tools.TableReference(
bigquery_tools.DatasetReference(new_project, copy_from_reference.dataset_id),
new_table_id)

Comment on lines 35 to +40
from google.api_core.exceptions import GoogleAPICallError

import apache_beam.io.gcp.bigquery
except ImportError:
GoogleAPICallError = None
bigquery = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In the try block, import apache_beam.io.gcp.bigquery is called, but bigquery is not bound to the local scope (only apache_beam is). In the except block, bigquery = None is set. If bigquery is accessed directly later in the file, it will raise a NameError when ImportError is not raised. Import it as import apache_beam.io.gcp.bigquery as bigquery instead.

Suggested change
from google.api_core.exceptions import GoogleAPICallError
import apache_beam.io.gcp.bigquery
except ImportError:
GoogleAPICallError = None
bigquery = None
from google.api_core.exceptions import GoogleAPICallError
import apache_beam.io.gcp.bigquery as bigquery
except ImportError:
GoogleAPICallError = None
bigquery = None

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants