Skip to content

feat(spanner): Add OPTIMISTIC and PESSIMISTIC read_lock_mode sample - #14922

Open
iennae wants to merge 3 commits into
feat/spanner-select-for-updatefrom
feat/spanner-read-lock-mode
Open

iennae wants to merge 3 commits into
feat/spanner-select-for-updatefrom
feat/spanner-read-lock-mode

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_read_lock_mode demonstrating client-level OPTIMISTIC and per-transaction PESSIMISTIC ReadLockMode configuration.

Note: Stacked on #14839 (feat/spanner-select-for-update) so this PR shows only this sample's diff. It will merge into main after #14839.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Concurrency tuning guides show configuring OPTIMISTIC or PESSIMISTIC read_lock_mode defaults on spanner.Client and overriding per transaction. Add a standalone spanner_read_lock_mode sample.
@iennae
iennae requested review from a team as code owners November 18, 2026 04:53
@product-auto-label product-auto-label Bot added api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples. labels Nov 18, 2026
@snippet-bot

snippet-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@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 introduces a new utility for configuring Spanner read lock modes, specifically demonstrating client-default OPTIMISTIC and per-transaction PESSIMISTIC locking. The reviewer identified a potential runtime error in the transaction logic where an empty result set could trigger an unhandled StopIteration exception, and suggested improving the robustness of the live integration test by ensuring the target row exists before execution.

Comment on lines +48 to +59
row = next(
iter(
transaction.execute_sql(
"SELECT AlbumTitle FROM Albums WHERE SingerId = 2 AND AlbumId = 1"
)
)
)
previous_title = str(row[0])
updated_rows = transaction.execute_update(
"UPDATE Albums SET AlbumTitle = 'A New Title' "
"WHERE SingerId = 2 AND AlbumId = 1"
)

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 the requested row does not exist in the Albums table, calling next(iter(...)) will raise a StopIteration exception, which is not caught by the try-except block and will cause the transaction to fail unexpectedly. Using next(iter(...), None) and checking for None provides a safer, more defensive approach.

        results = transaction.execute_sql(
            "SELECT AlbumTitle FROM Albums WHERE SingerId = 2 AND AlbumId = 1"
        )
        row = next(iter(results), None)
        if row is not None:
            previous_title = str(row[0])
            updated_rows = transaction.execute_update(
                "UPDATE Albums SET AlbumTitle = 'A New Title' "
                "WHERE SingerId = 2 AND AlbumId = 1"
            )

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.

Good catch, done: the lookup uses next(iter(...), None) and raises a descriptive error if the row is missing, which the sample reports on stderr (ca58479).

Comment on lines +133 to +149
try:
read_lock_mode.run_transaction_with_read_lock_mode(
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 "Updated Rows: 1" in out
finally:
with db.batch() as batch:
batch.update(
table="Albums",
columns=("SingerId", "AlbumId", "AlbumTitle"),
values=[(2, 1, "Green")],
)

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

The live integration test expects to update exactly 1 row. However, if the target row does not exist in the database prior to running the test, the transaction will update 0 rows, causing the assertion to fail. Ensuring the row exists by performing an insert_or_update operation before running the transaction makes the test robust and self-contained.

    # Ensure the target row exists before running the transaction
    with db.batch() as batch:
        batch.insert_or_update(
            table="Albums",
            columns=("SingerId", "AlbumId", "AlbumTitle"),
            values=[(2, 1, "Green")],
        )

    try:
        read_lock_mode.run_transaction_with_read_lock_mode(
            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 "Updated Rows: 1" in out
    finally:
        with db.batch() as batch:
            batch.insert_or_update(
                table="Albums",
                columns=("SingerId", "AlbumId", "AlbumTitle"),
                values=[(2, 1, "Green")],
            )

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.

Done: the live test inserts-or-updates the row before running and restores it in finally (ca58479).

Problem: review of this sample identified correctness and robustness
improvements in the sample and its tests.

Solution: apply the accepted review suggestions and extend the tests to
cover the updated behavior. Details are in the review thread replies.

Files updated:
  - spanner/transactions/src/spanner_transactions/read_lock_mode.py
  - spanner/transactions/tests/read_lock_mode_test.py
Problem: multi-line SQL and DDL statements were written as adjacent string
fragments. That style is easy to get wrong (a missing trailing space joins
two SQL tokens) and is harder to read than the statement itself, and the
samples in this set mixed it with triple-quoted SQL.

Solution: write each multi-line statement as a single triple-quoted string,
matching the layout already used by the other samples. Only whitespace
between SQL tokens changes; the statements are otherwise identical.

Files updated:
  - spanner/transactions/src/spanner_transactions/read_lock_mode.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant