Repository navigation
fix(spanner): forward client_options in spanner_dbapi.connect() - #19183
Conversation
## Problem Statement - Calling `spanner_dbapi.connect()` with `client_options` on standard Cloud Spanner connections (using Application Default Credentials, explicit `Credentials`, or a service account JSON path) silently ignored `client_options` and fell back to the default Spanner endpoint instead of honoring settings such as `universe_domain` or `api_endpoint`. - Passing `client_options` alongside a pre-built `client` was also silently ignored instead of raising an error. ## Solution - Added `client_options` as an explicit optional parameter on `spanner_dbapi.connect()` so it is never stored as a connection variable on `Connection`. - Forwarded `client_options` (`ClientOptions` or `dict`) to `spanner.Client` and `spanner.Client.from_service_account_json()` across all connection modes. - Raised `ValueError` when both a pre-built `client` and non-`None` `client_options` are supplied to `spanner_dbapi.connect()` so custom client options are never silently ignored.
There was a problem hiding this comment.
Code Review
This pull request adds support for client_options in the Spanner DB-API connect function, allowing configuration of custom endpoints and universe domains. It also prevents client_options from being silently ignored when a custom client is provided. However, the newly added end-to-end tests in test_connection.py fail to provide the required database_id positional argument to the connect function, which will cause TypeError exceptions when the tests are run.
There was a problem hiding this comment.
Code Review
This pull request adds support for the client_options parameter in the Spanner DB-API connect function, allowing users to configure options like api_endpoint and universe_domain. It updates the connection logic to pass these options to the client, prevents their use when a custom client is provided, and adds comprehensive unit tests to validate various scenarios. I have no feedback to provide as the changes are well-implemented and thoroughly tested.
|
Shouldn't this be marked as a fix instead of a chore? Chores aren't shown in release notes, and IIRC won't trigger a new release PR on their own |
olavloite
left a comment
There was a problem hiding this comment.
Note on context: client_options in spanner_dbapi.connect() originally started in #1370 as a test-only kwargs hook (gated on AnonymousCredentials), became an implicit public option in #17246 when connect()'s docstring recommended it for Spanner Omni, and is now being formalized as an explicit connection parameter. Since tightening existing overlapping options into errors would now be a breaking change, documenting precedence clearly is especially important.
A few cleanups to address before merging:
-
Validate and unify
client_optionshandling ingoogle/cloud/spanner_dbapi/connection.py:- Move
import copyfrom line 1039 to the top of the module. - Extract the
omniclient_optionsresolution and shallow-copy logic (lines 996–1000 and 1033–1042) into a small helper that validatesclient_optionstype. Passing a non-dict, non-ClientOptionsobject alongsideexperimental_hostcurrently hitscopy.copy(client_options).api_endpoint = host_endpointand raisesAttributeErrorinstead ofTypeError/ValueError, and the fallback branch at line 999 is also uncovered by tests.
- Move
-
Assert the exception message in
tests/unit/spanner_dbapi/test_connection.py(line 1027):- Replace bare
with self.assertRaises(ValueError):withassertRaisesRegex(or assert onctx.exception) to verify the expected error message.
- Replace bare
-
Document precedence and fix docstring ordering in
connect()(google/cloud/spanner_dbapi/connection.py):- Document precedence/interactions for the overlapping connection options (
SPANNER_EMULATOR_HOSToverridingcredentials/instance_type/api_endpoint,experimental_hostoverridingclient_options.api_endpoint,instance_type="omni"overridingprojectandcredentials, anduse_plain_text/Omni TLS parameters only applying wheninstance_type="omni"). - Move
:param client_options:above:returns:/:rtype:.
- Document precedence/interactions for the overlapping connection options (
-
Squash-merge commit title:
- Ensure the squash commit uses the
fix(spanner): ...PR title rather than the localchore(spanner): ...commit message so it is included in release notes and triggers a release PR.
- Ensure the squash commit uses the
|
@olavloite Thanks for the review! Addressed all 4 items in the latest commit: moved |
olavloite
left a comment
There was a problem hiding this comment.
LGTM.
There are a few minor (pre-existing) inconsistencies in the docstring remaining, but feel free to merge as-is, as the current implementation is a significant improvement.
-
SPANNER_EMULATOR_HOSTvs.instance_type="omni"andcredentialsfile paths- In
connect(), theinstance_type == "omni"block runs beforespanner.Client(...)checksSPANNER_EMULATOR_HOST. As a result, callingconnect(..., instance_type="omni")withoutapi_endpoint/experimental_hostraisesValueErroreven whenSPANNER_EMULATOR_HOSTis set (whereasspanner.Client(..., instance_type="omni")connects to the emulator). When an endpoint is provided alongsideSPANNER_EMULATOR_HOST,connect()also overwritesprojectto"default"beforespanner.Clientswitches to the emulator. - When
credentialsis a file path (str),Client.from_service_account_json()is still called and reads the file from disk beforespanner.Clientoverridescredentialsfor the emulator.
- In
-
credentialsas a file path (str) bypassesexperimental_hostandinstance_type- Because
if isinstance(credentials, str):wraps theexperimental_host/instance_typelogic in anelse:branch, passing a credential file path together withinstance_type="omni"(or an invalidinstance_type),experimental_host, or Omni TLS/auth options silently ignores those options and connects viaClient.from_service_account_json().
- Because
-
username/passwordwheninstance_type != "omni"connect()does not forwardusernameorpasswordtospanner.Client(...), so passing them withoutinstance_type="omni"(orexperimental_host) silently ignores them instead of raisingValueErrorasspanner.Client(...)does. When migrating fromexperimental_hosttoclient_options={"api_endpoint": ...}, forgettinginstance_type="omni"will therefore fall back tocredentials/ ADC and ignoreca_certificate/ mTLS options.
I think that this docstring would describe the actual behavior a bit better:
.. note::
**Option precedence and interactions:**
- ``credentials`` as a file path (``str``) takes precedence over
``experimental_host``, ``instance_type``, and the Omni auth/TLS
options, connecting via :meth:`Client.from_service_account_json`.
- ``SPANNER_EMULATOR_HOST`` (environment variable) overrides
``credentials`` (unless passed as a ``str`` file path, which is
still loaded before the override) and ``api_endpoint`` to connect
to the Spanner emulator using anonymous credentials. Note that
``instance_type="omni"`` still validates that an endpoint is set
and overrides ``project`` to ``"default"`` before
``SPANNER_EMULATOR_HOST`` takes effect.
- ``experimental_host`` (deprecated) forces ``instance_type="omni"``
(overriding any ``instance_type`` value) and overrides
``client_options.api_endpoint``.
- ``instance_type="omni"`` (when ``credentials`` is not a ``str``)
overrides ``project`` (to ``"default"``) and ``credentials``
(using ``SpannerOmniCredentials`` when both ``username`` and
``password`` are provided, or ``AnonymousCredentials`` otherwise).
- ``use_plain_text``, ``ca_certificate``, ``client_certificate``,
``client_key``, ``username``, and ``password`` apply only when
``instance_type="omni"`` (and ``credentials`` is not a ``str``),
and are silently ignored otherwise.
- Providing both a custom ``client`` and non-``None``
``client_options`` raises :class:`ValueError` (other client-creation
options are ignored when a custom ``client`` is provided).|
@olavloite Good points — updated the |
## Problem Statement - Calling `spanner_dbapi.connect()` with `client_options` on standard Cloud Spanner connections (using Application Default Credentials, explicit `Credentials`, or a service account JSON path) silently ignored `client_options` and fell back to the default Spanner endpoint instead of honoring settings such as `universe_domain` or `api_endpoint`. - Passing `client_options` alongside a pre-built `client` was also silently ignored instead of raising an error. ## Solution - Added `client_options` as an explicit optional parameter on `spanner_dbapi.connect()` so it is never stored as a connection variable on `Connection`. - Forwarded `client_options` (`ClientOptions` or `dict`) to `spanner.Client` and `spanner.Client.from_service_account_json()` across all connection modes. - Raised `ValueError` when both a pre-built `client` and non-`None` `client_options` are supplied to `spanner_dbapi.connect()` so custom client options are never silently ignored.
Problem Statement
spanner_dbapi.connect()withclient_optionson standard Cloud Spanner connections (using Application Default Credentials, explicitCredentials, or a service account JSON path) silently ignoredclient_optionsand fell back to the default Spanner endpoint instead of honoring settings such asuniverse_domainorapi_endpoint.client_optionsalongside a pre-builtclientwas also silently ignored instead of raising an error.Solution
client_optionsas an explicit optional parameter onspanner_dbapi.connect()so it is never stored as a connection variable onConnection.client_options(ClientOptionsordict) tospanner.Clientandspanner.Client.from_service_account_json()across all connection modes.ValueErrorwhen both a pre-builtclientand non-Noneclient_optionsare supplied tospanner_dbapi.connect()so custom client options are never silently ignored.