From 22665a004674135d6207160bdf12596f8b560035 Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 10:25:49 -0500 Subject: [PATCH] fix(pandas-gbq): reuse bigquery_client in GbqConnector.get_client and support client_options --- packages/pandas-gbq/pandas_gbq/gbq.py | 4 + .../pandas-gbq/pandas_gbq/gbq_connector.py | 39 +++--- .../tests/unit/test_universe_domain.py | 124 ++++++++++++++++++ 3 files changed, 150 insertions(+), 17 deletions(-) create mode 100644 packages/pandas-gbq/tests/unit/test_universe_domain.py diff --git a/packages/pandas-gbq/pandas_gbq/gbq.py b/packages/pandas-gbq/pandas_gbq/gbq.py index 09b40341860e..d9c9991f9740 100644 --- a/packages/pandas-gbq/pandas_gbq/gbq.py +++ b/packages/pandas-gbq/pandas_gbq/gbq.py @@ -133,6 +133,7 @@ def read_gbq( col_order=None, bigquery_client=None, dry_run: bool = False, + client_options=None, ): r"""Read data from Google BigQuery to a pandas DataFrame. @@ -335,6 +336,7 @@ def read_gbq( client_id=client_id, client_secret=client_secret, bigquery_client=bigquery_client, + client_options=client_options, ) if _is_query(query_or_table): @@ -419,6 +421,7 @@ def to_gbq( user_agent=None, rfc9110_delimiter=False, bigquery_client=None, + client_options=None, ): """Write a DataFrame to a Google BigQuery table. @@ -621,6 +624,7 @@ def to_gbq( user_agent=user_agent, rfc9110_delimiter=rfc9110_delimiter, bigquery_client=bigquery_client, + client_options=client_options, ) bqclient = connector.client diff --git a/packages/pandas-gbq/pandas_gbq/gbq_connector.py b/packages/pandas-gbq/pandas_gbq/gbq_connector.py index 3a4769379ba7..f9aa856a6859 100644 --- a/packages/pandas-gbq/pandas_gbq/gbq_connector.py +++ b/packages/pandas-gbq/pandas_gbq/gbq_connector.py @@ -52,6 +52,7 @@ def __init__( user_agent=None, rfc9110_delimiter=False, bigquery_client=None, + client_options=None, ): from pandas_gbq import auth @@ -69,6 +70,7 @@ def __init__( self.user_agent = user_agent self.rfc9110_delimiter = rfc9110_delimiter self.use_bqstorage_api = use_bqstorage_api + self.client_options = client_options if bigquery_client is not None: # If a bq client is already provided, use it to populate auth fields. @@ -114,7 +116,11 @@ def __init__( context.project = self.project_id self.client = _get_client( - self.user_agent, self.rfc9110_delimiter, self.project_id, self.credentials + self.user_agent, + self.rfc9110_delimiter, + self.project_id, + self.credentials, + client_options=self.client_options, ) def _start_timer(self): @@ -129,21 +135,14 @@ def log_elapsed_seconds(self, prefix="Elapsed", postfix="s.", overlong=6): logger.info("{} {} {}".format(prefix, sec, postfix)) def get_client(self): - import google.api_core.client_info - - bigquery = FEATURES.bigquery_try_import() - - user_agent = create_user_agent( - user_agent=self.user_agent, rfc9110_delimiter=self.rfc9110_delimiter - ) - - client_info = google.api_core.client_info.ClientInfo( - user_agent=user_agent, - ) - return bigquery.Client( - project=self.project_id, - credentials=self.credentials, - client_info=client_info, + if getattr(self, "client", None) is not None: + return self.client + return _get_client( + self.user_agent, + self.rfc9110_delimiter, + self.project_id, + self.credentials, + client_options=getattr(self, "client_options", None), ) @staticmethod @@ -302,7 +301,9 @@ def load_data( self.process_http_error(ex) -def _get_client(user_agent, rfc9110_delimiter, project_id, credentials): +def _get_client( + user_agent, rfc9110_delimiter, project_id, credentials, client_options=None +): import google.api_core.client_info bigquery = FEATURES.bigquery_try_import() @@ -314,10 +315,14 @@ def _get_client(user_agent, rfc9110_delimiter, project_id, credentials): client_info = google.api_core.client_info.ClientInfo( user_agent=user_agent, ) + kwargs = {} + if client_options is not None: + kwargs["client_options"] = client_options return bigquery.Client( project=project_id, credentials=credentials, client_info=client_info, + **kwargs, ) diff --git a/packages/pandas-gbq/tests/unit/test_universe_domain.py b/packages/pandas-gbq/tests/unit/test_universe_domain.py new file mode 100644 index 000000000000..49e2c44308bc --- /dev/null +++ b/packages/pandas-gbq/tests/unit/test_universe_domain.py @@ -0,0 +1,124 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. + +"""Unit tests for client_options, universe_domain, and bigquery_client reuse.""" + +from types import MappingProxyType +from unittest import mock + +import pandas as pd +import pytest +from google.api_core import client_options as client_options_lib +from google.auth import credentials as auth_credentials + +import pandas_gbq +from pandas_gbq import gbq_connector + +CUSTOM_UNIVERSE = "apis-tpclp.goog" + + +def test_gbq_connector_get_client_reuses_supplied_bigquery_client(): + supplied_client = mock.Mock( + project="tpc-proj", + _credentials=auth_credentials.AnonymousCredentials(), + ) + + connector = gbq_connector.GbqConnector( + project_id=None, + bigquery_client=supplied_client, + ) + + assert connector.client is supplied_client + assert connector.get_client() is supplied_client + + +@pytest.mark.parametrize( + "opts", + [ + pytest.param( + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + id="client_options_instance", + ), + pytest.param({"universe_domain": CUSTOM_UNIVERSE}, id="dict"), + pytest.param( + MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}), + id="mapping_proxy", + ), + ], +) +def test_gbq_connector_forwards_client_options(opts): + fake_creds = auth_credentials.AnonymousCredentials() + with mock.patch.object( + gbq_connector.FEATURES, "bigquery_try_import" + ) as mock_bq_import: + mock_bq = mock_bq_import.return_value + connector = gbq_connector.GbqConnector( + project_id="tpc-proj", + credentials=fake_creds, + client_options=opts, + ) + + mock_bq.Client.assert_called_once() + assert mock_bq.Client.call_args.kwargs["client_options"] is opts + assert connector.get_client() is mock_bq.Client.return_value + + +def test_gbq_connector_get_client_fallback_forwards_client_options(): + opts = client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE) + fake_creds = auth_credentials.AnonymousCredentials() + with mock.patch.object( + gbq_connector.FEATURES, "bigquery_try_import" + ) as mock_bq_import: + mock_bq = mock_bq_import.return_value + connector = gbq_connector.GbqConnector( + project_id="tpc-proj", + credentials=fake_creds, + client_options=opts, + ) + connector.client = None + connector.get_client() + + assert mock_bq.Client.call_count == 2 + assert mock_bq.Client.call_args.kwargs["client_options"] is opts + + +def test_read_gbq_forwards_client_options(): + opts = {"universe_domain": CUSTOM_UNIVERSE} + with mock.patch("pandas_gbq.gbq.GbqConnector") as mock_connector_cls: + mock_connector_cls.return_value.run_query.return_value = pd.DataFrame() + pandas_gbq.read_gbq( + "SELECT 1", + project_id="tpc-proj", + client_options=opts, + ) + + assert mock_connector_cls.call_args.kwargs["client_options"] is opts + + +def test_to_gbq_forwards_client_options(): + opts = client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE) + df = pd.DataFrame({"a": [1]}) + with mock.patch("pandas_gbq.gbq.GbqConnector") as mock_connector_cls: + mock_connector = mock_connector_cls.return_value + mock_connector.project_id = "tpc-proj" + mock_connector.client.get_table.side_effect = Exception("stop") + with pytest.raises(Exception, match="stop"): + pandas_gbq.to_gbq( + df, + "ds.tbl", + project_id="tpc-proj", + client_options=opts, + ) + + assert mock_connector_cls.call_args.kwargs["client_options"] is opts