diff --git a/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/_helpers.py b/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/_helpers.py index 2977860d122f..4b2bd10e362b 100644 --- a/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/_helpers.py +++ b/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/_helpers.py @@ -5,14 +5,17 @@ # https://opensource.org/licenses/MIT. import base64 +import copy import functools import json import re -from typing import Optional +from collections.abc import Mapping +from typing import Any, Optional import google.auth import sqlalchemy from google.api_core import client_info +from google.api_core import client_options as client_options_lib from google.cloud import bigquery from google.oauth2 import service_account @@ -37,6 +40,40 @@ def google_client_info( return client_info.ClientInfo(user_agent=user_agent) +# TODO(https://github.com/googleapis/google-cloud-python/issues/19297): Replace with +# google.api_core.client_options.normalize_client_options once available and +# minimum allowed google-api-core version exceeds that release. +def _normalize_client_options( + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None, +) -> client_options_lib.ClientOptions | None: + """Normalize ``client_options`` to a fresh ``ClientOptions`` copy or ``None``. + + Args: + client_options: Optional ``ClientOptions`` instance, ``Mapping``, or + ``None``. + + Returns: + A fresh ``ClientOptions`` copy, or ``None`` if ``client_options`` is + ``None``. + + Raises: + TypeError: If ``client_options`` is not a ``ClientOptions`` instance, + ``Mapping``, or ``None``. + ValueError: If ``client_options`` is a ``Mapping`` containing an + unrecognized option name. + """ + if client_options is None: + return None + if isinstance(client_options, Mapping): + return client_options_lib.from_dict(client_options) + if isinstance(client_options, client_options_lib.ClientOptions): + return copy.copy(client_options) + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or None; " + f"got {type(client_options).__name__}" + ) + + def create_bigquery_client( credentials_info: Optional[dict] = None, credentials_path: Optional[str] = None, @@ -45,6 +82,7 @@ def create_bigquery_client( location: Optional[str] = None, project_id: Optional[str] = None, user_agent: Optional[google.api_core.client_info.ClientInfo] = None, + client_options: client_options_lib.ClientOptions | Mapping[str, Any] | None = None, ) -> google.cloud.bigquery.Client: """Construct a BigQuery client object. @@ -64,6 +102,10 @@ def create_bigquery_client( requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own library or partner tool. + client_options (client_options_lib.ClientOptions | Mapping[str, Any] | None): + Client options (such as ``universe_domain`` or ``api_endpoint``) + forwarded to ``google.cloud.bigquery.Client``. If ``None``, default + client options are used. """ default_project = None @@ -90,6 +132,7 @@ def create_bigquery_client( project_id = default_project client_info = google_client_info(user_agent=user_agent) + client_options = _normalize_client_options(client_options) return bigquery.Client( client_info=client_info, @@ -97,6 +140,7 @@ def create_bigquery_client( credentials=credentials, location=location, default_query_job_config=default_query_job_config, + client_options=client_options, ) diff --git a/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/base.py b/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/base.py index a0ba022c9d05..440455a4bab7 100644 --- a/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/base.py +++ b/packages/sqlalchemy-bigquery/sqlalchemy_bigquery/base.py @@ -1357,6 +1357,7 @@ def __init__( credentials_info=None, credentials_base64=None, list_tables_page_size=1000, + client_options=None, *args, **kwargs, ): @@ -1371,6 +1372,7 @@ def __init__( self.identifier_preparer = self.preparer(self) self.dataset_id = None self.list_tables_page_size = list_tables_page_size + self.client_options = client_options @classmethod def dbapi(cls): @@ -1435,13 +1437,13 @@ def create_connect_args(self, url): # The user is expected to supply a client with # create_engine('...', connect_args={'client': bq_client}) return ([], {}) - client = _helpers.create_bigquery_client( credentials_path=self.credentials_path, credentials_info=self.credentials_info, credentials_base64=self.credentials_base64, project_id=self.billing_project_id, location=self.location, + client_options=self.client_options, ) # If the user specified `bigquery://` or `bigquery:///dataset` we need # to set the project_id from the client before constructing the job diff --git a/packages/sqlalchemy-bigquery/tests/unit/test_universe_domain.py b/packages/sqlalchemy-bigquery/tests/unit/test_universe_domain.py new file mode 100644 index 000000000000..22df70baa2fe --- /dev/null +++ b/packages/sqlalchemy-bigquery/tests/unit/test_universe_domain.py @@ -0,0 +1,204 @@ +# Copyright 2026 The sqlalchemy-bigquery Authors +# +# Use of this source code is governed by an MIT-style +# license that can be found in the LICENSE file or at +# https://opensource.org/licenses/MIT. + +"""Unit tests for client_options and universe_domain forwarding.""" + +import types +from unittest import mock + +import pytest +import sqlalchemy +from google.api_core import client_options as client_options_lib +from google.auth import credentials as auth_credentials +from google.cloud import bigquery + +from sqlalchemy_bigquery import _helpers, base + +CUSTOM_UNIVERSE = "apis-tpclp.goog" +DEFAULT_UNIVERSE = "googleapis.com" +DEFAULT_PROJECT_ID = "test-proj" +DEFAULT_DATASET_ID = "test_ds" + + +@pytest.fixture +def anonymous_creds(): + return auth_credentials.AnonymousCredentials() + + +@pytest.mark.parametrize( + ("client_options", "expected_universe"), + [ + pytest.param( + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + CUSTOM_UNIVERSE, + id="client_options_instance", + ), + pytest.param( + {"universe_domain": CUSTOM_UNIVERSE}, + CUSTOM_UNIVERSE, + id="dict", + ), + pytest.param( + types.MappingProxyType({"universe_domain": CUSTOM_UNIVERSE}), + CUSTOM_UNIVERSE, + id="mapping_proxy", + ), + pytest.param({}, DEFAULT_UNIVERSE, id="empty_dict"), + pytest.param(None, DEFAULT_UNIVERSE, id="none"), + ], +) +def test_create_bigquery_client_constructs_real_client( + anonymous_creds, client_options, expected_universe +): + with mock.patch.object( + _helpers.google.auth, + "default", + autospec=True, + return_value=(anonymous_creds, DEFAULT_PROJECT_ID), + ): + client = _helpers.create_bigquery_client(client_options=client_options) + + assert isinstance(client, bigquery.Client) + assert client.project == DEFAULT_PROJECT_ID + if hasattr(client, "universe_domain"): + assert client.universe_domain == expected_universe + + +def test_create_bigquery_client_default_omitted(anonymous_creds): + with ( + mock.patch.object( + _helpers.google.auth, + "default", + autospec=True, + return_value=(anonymous_creds, DEFAULT_PROJECT_ID), + ), + mock.patch.object(_helpers.bigquery, "Client", autospec=True) as mock_client, + ): + _helpers.create_bigquery_client() + + mock_client.assert_called_once() + assert mock_client.call_args.kwargs["client_options"] is None + + +def test_create_bigquery_client_invalid_client_options_raises(anonymous_creds): + with mock.patch.object( + _helpers.google.auth, + "default", + autospec=True, + return_value=(anonymous_creds, DEFAULT_PROJECT_ID), + ): + with pytest.raises( + TypeError, + match="client_options must be a ClientOptions instance, Mapping, or None", + ): + _helpers.create_bigquery_client( + client_options="invalid" # type: ignore[arg-type] + ) + + +def test_create_bigquery_client_copies_client_options(anonymous_creds): + caller_opts = client_options_lib.ClientOptions(quota_project_id="qp-1") + with ( + mock.patch.object( + _helpers.google.auth, + "default", + autospec=True, + return_value=(anonymous_creds, DEFAULT_PROJECT_ID), + ), + mock.patch.object(_helpers.bigquery, "Client", autospec=True) as mock_client, + ): + _helpers.create_bigquery_client(client_options=caller_opts) + + forwarded = mock_client.call_args.kwargs["client_options"] + assert forwarded is not caller_opts + assert forwarded.quota_project_id == "qp-1" + + +def test_dialect_forwards_client_options_to_create_bigquery_client(): + client_options = client_options_lib.ClientOptions( + universe_domain=CUSTOM_UNIVERSE, + api_endpoint=f"https://bigquery.{CUSTOM_UNIVERSE}", + ) + dialect = base.BigQueryDialect(client_options=client_options) + url = sqlalchemy.engine.url.make_url( + f"bigquery://{DEFAULT_PROJECT_ID}/{DEFAULT_DATASET_ID}" + ) + fake_client = mock.create_autospec(bigquery.Client, instance=True) + fake_client.project = DEFAULT_PROJECT_ID + mock.seal(fake_client) + + with mock.patch.object( + _helpers, "create_bigquery_client", autospec=True, return_value=fake_client + ) as mock_create: + dialect.create_connect_args(url) + + mock_create.assert_called_once() + assert mock_create.call_args.kwargs["client_options"] is client_options + + +def test_dialect_default_client_options_none(): + dialect = base.BigQueryDialect() + url = sqlalchemy.engine.url.make_url( + f"bigquery://{DEFAULT_PROJECT_ID}/{DEFAULT_DATASET_ID}" + ) + fake_client = mock.create_autospec(bigquery.Client, instance=True) + fake_client.project = DEFAULT_PROJECT_ID + mock.seal(fake_client) + + with mock.patch.object( + _helpers, "create_bigquery_client", autospec=True, return_value=fake_client + ) as mock_create: + dialect.create_connect_args(url) + + mock_create.assert_called_once() + assert mock_create.call_args.kwargs["client_options"] is None + + +@pytest.mark.parametrize( + "client_options", + [ + pytest.param( + client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE), + id="client_options_instance", + ), + pytest.param({"universe_domain": CUSTOM_UNIVERSE}, id="dict"), + pytest.param(None, id="none"), + ], +) +def test_create_engine_accepts_and_forwards_client_options(client_options): + engine = sqlalchemy.create_engine( + f"bigquery://{DEFAULT_PROJECT_ID}/{DEFAULT_DATASET_ID}", + client_options=client_options, + ) + fake_client = mock.create_autospec(bigquery.Client, instance=True) + fake_client.project = DEFAULT_PROJECT_ID + mock.seal(fake_client) + + assert engine.dialect.client_options is client_options + + with mock.patch.object( + _helpers, "create_bigquery_client", autospec=True, return_value=fake_client + ) as mock_create: + engine.dialect.create_connect_args(engine.url) + + mock_create.assert_called_once() + assert mock_create.call_args.kwargs["client_options"] is client_options + + +def test_create_engine_user_supplied_client_skips_create_bigquery_client(): + engine = sqlalchemy.create_engine( + f"bigquery://{DEFAULT_PROJECT_ID}/{DEFAULT_DATASET_ID}?user_supplied_client=true", + client_options={"universe_domain": CUSTOM_UNIVERSE}, + ) + + with mock.patch.object( + _helpers, "create_bigquery_client", autospec=True + ) as mock_create: + args, kwargs = engine.dialect.create_connect_args(engine.url) + + mock_create.assert_not_called() + assert args == [] + assert kwargs == {}