Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions spanner/transactions/src/spanner_transactions/directed_read.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# 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.

# [START spanner_directed_read]
import sys

from google.api_core import exceptions
from google.cloud import spanner
from google.cloud import spanner_v1


def directed_read(project_id: str, instance_id: str, database_id: str) -> None:
"""Executes a snapshot SQL read using client and per-request DirectedReadOptions.

Args:
project_id: The Google Cloud project ID.
instance_id: The Spanner instance ID.
database_id: The Spanner database ID containing Albums.
"""
Comment on lines +23 to +30

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

Allow project_id to be optional (str | None) so that the Spanner client can automatically infer the project ID from Application Default Credentials (ADC) when it is not explicitly provided.

def directed_read(
    project_id: str | None, instance_id: str, database_id: str
) -> None:
    """Executes a snapshot SQL read using client and per-request DirectedReadOptions.

    Args:
        project_id: The Google Cloud project ID. If None, it is inferred from ADC.
        instance_id: The Spanner instance ID.
        database_id: The Spanner database ID containing Albums.
    """

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

excluded_replica = spanner_v1.DirectedReadOptions.ReplicaSelection(
location="us-east4"
)
exclude_replicas = spanner_v1.DirectedReadOptions.ExcludeReplicas(
replica_selections=[excluded_replica]
)
client_directed_options = spanner_v1.DirectedReadOptions(
exclude_replicas=exclude_replicas
)

client = spanner.Client(
project=project_id, directed_read_options=client_directed_options
)
database = client.instance(instance_id).database(database_id)

read_only_replica = spanner_v1.DirectedReadOptions.ReplicaSelection(
type_=spanner_v1.DirectedReadOptions.ReplicaSelection.Type.READ_ONLY
)
include_replicas = spanner_v1.DirectedReadOptions.IncludeReplicas(
replica_selections=[read_only_replica],
auto_failover_disabled=False,
)
request_directed_options = spanner_v1.DirectedReadOptions(
include_replicas=include_replicas
)

try:
with database.snapshot() as snapshot:
rows = list(
snapshot.execute_sql(
"SELECT SingerId, AlbumId, AlbumTitle FROM Albums",
directed_read_options=request_directed_options,
)
)
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: directed read query failed on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
else:
print(f"Resource ID: {database_id}")
for singer_id, album_id, album_title in rows:
print(f"Album ID: {album_id}, Singer ID: {singer_id}, Title: {album_title}")
print(f"Row Count: {len(rows)}")


# [END spanner_directed_read]


if __name__ == "__main__":
import argparse
import os

parser = argparse.ArgumentParser(
description="Route read-only snapshot queries using Spanner DirectedReadOptions."
)
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
Comment on lines +94 to +98

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

Change the default value of --project-id to os.environ.get("GOOGLE_CLOUD_PROJECT") (which defaults to None if not set) instead of a hardcoded fallback string like "example-project-id". This allows the Spanner client to fall back to Application Default Credentials (ADC) to infer the project ID when neither the command-line argument nor the environment variable is provided.

Suggested change
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
parser.add_argument(
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

parser.add_argument(
"--instance-id",
default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"),
help="Spanner instance ID (default: $SPANNER_INSTANCE_ID)",
)
parser.add_argument(
"--database-id",
default=os.environ.get("SPANNER_DATABASE_ID", "example-db"),
help="Spanner database ID (default: $SPANNER_DATABASE_ID)",
)
args = parser.parse_args()

directed_read(
project_id=args.project_id,
instance_id=args.instance_id,
database_id=args.database_id,
)
119 changes: 119 additions & 0 deletions spanner/transactions/tests/directed_read_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# 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.

import runpy
from unittest import mock

from google.api_core import exceptions
import pytest
from spanner_transactions import directed_read

from . import conftest

PROJECT_ID = "example-project-id"
INSTANCE_ID = "example-instance"
DATABASE_ID = "example-db"
SPANNER_CLIENT = "google.cloud.spanner.Client"


@mock.patch(SPANNER_CLIENT)
def test_directed_read_success(
mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str]
) -> None:
snapshot = (
mock_client_class.return_value.instance.return_value.database.return_value.snapshot.return_value.__enter__.return_value
)
snapshot.execute_sql.return_value = [(1, 1, "Total Junk")]

directed_read.directed_read(PROJECT_ID, INSTANCE_ID, DATABASE_ID)

assert "directed_read_options" in mock_client_class.call_args.kwargs
assert "directed_read_options" in snapshot.execute_sql.call_args.kwargs
out, err = capsys.readouterr()
assert f"Resource ID: {DATABASE_ID}" in out
assert "Album ID: 1, Singer ID: 1, Title: Total Junk" in out
assert "Row Count: 1" in out
assert PROJECT_ID not in out
assert err == ""


@pytest.mark.parametrize(
"error, expected_prefix",
[
(exceptions.NotFound("missing"), "error: database 'example-db'"),
(
exceptions.InvalidArgument("bad replica"),
"error: directed read query failed",
),
],
)
@mock.patch(SPANNER_CLIENT)
def test_directed_read_errors(
mock_client_class: mock.MagicMock,
capsys: pytest.CaptureFixture[str],
error: Exception,
expected_prefix: str,
) -> None:
snapshot = (
mock_client_class.return_value.instance.return_value.database.return_value.snapshot.return_value.__enter__.return_value
)
snapshot.execute_sql.side_effect = error

directed_read.directed_read(PROJECT_ID, INSTANCE_ID, DATABASE_ID)

out, err = capsys.readouterr()
assert out == ""
assert err.startswith(expected_prefix)
assert PROJECT_ID not in err


@mock.patch(SPANNER_CLIENT)
def test_directed_read_cli_entrypoint(
mock_client_class: mock.MagicMock,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
snapshot = (
mock_client_class.return_value.instance.return_value.database.return_value.snapshot.return_value.__enter__.return_value
)
snapshot.execute_sql.return_value = [(1, 1, "Total Junk")]
monkeypatch.setattr(
"sys.argv",
[
"directed_read.py",
"--project-id",
PROJECT_ID,
"--instance-id",
INSTANCE_ID,
"--database-id",
DATABASE_ID,
],
)

runpy.run_module("spanner_transactions.directed_read", run_name="__main__")

assert "Row Count: 1" in capsys.readouterr().out


@conftest.live_only
def test_directed_read_live(capsys: pytest.CaptureFixture[str]) -> None:
directed_read.directed_read(
conftest.LIVE_PROJECT_ID,
conftest.LIVE_INSTANCE_ID,
conftest.LIVE_DATABASE_ID,
)
out, err = capsys.readouterr()
assert err == ""
assert conftest.LIVE_PROJECT_ID not in out
assert "Total Junk" in out