Skip to content

feat(spanner): Add GoogleSQL UPDATE DML THEN RETURN sample - #14861

Open
iennae wants to merge 3 commits into
feat/spanner-dml-last-statementfrom
feat/spanner-update-dml-returning
Open

iennae wants to merge 3 commits into
feat/spanner-dml-last-statementfrom
feat/spanner-update-dml-returning

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Using UPDATE ... THEN RETURN returns computed column values directly from the update statement inside a read-write transaction.

Adds spanner_update_dml_returning using the canonical cross-language region tag.

Note: Stacked on #14850 (feat/spanner-dml-last-statement) so this PR shows only this sample's diff. It will merge into main after #14850.

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

Returning updated column values directly from an UPDATE statement avoids an extra read round trip inside read-write transactions.
@iennae
iennae requested review from a team as code owners November 17, 2026 23:47
@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 17, 2026
@snippet-bot

snippet-bot Bot commented Nov 17, 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 sample and tests demonstrating how to execute a Spanner DML update with a 'THEN RETURN' clause in Python. The reviewer provided valuable feedback suggesting a more idiomatic approach: instead of using and clearing outer-scope mutable lists within the transaction callback, the callback should return the results directly since database.run_in_transaction propagates the callback's return value. This avoids side-effects on retries.

Comment on lines +33 to +67
budgets: list[int] = []
row_counts: list[int] = []

def update_albums(transaction: spanner_v1.Transaction) -> None:
budgets.clear()
row_counts.clear()
results = transaction.execute_sql(
"UPDATE Albums "
"SET MarketingBudget = MarketingBudget * 2 "
"WHERE SingerId = 1 AND AlbumId = 1 "
"THEN RETURN MarketingBudget"
)
for row in results:
budgets.append(int(row[0] or 0))
row_counts.append(int(results.stats.row_count_exact))

try:
database.run_in_transaction(update_albums)
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' on instance '{instance_id}' "
f"in project '{project_id}' was not found: {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: UPDATE DML RETURNING failed on database '{database_id}' "
f"in instance '{instance_id}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
else:
print(f"Resource ID: {database.name}")
for budget in budgets:
print(f"Marketing Budget: {budget}")
print(f"Updated Rows: {row_counts[-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

In Cloud Spanner's Python SDK, database.run_in_transaction returns the return value of the callback function. Instead of using outer-scope mutable lists (budgets and row_counts) and manually clearing them on retries, it is much cleaner and more idiomatic to return the results directly from the transaction function as a tuple. This avoids side-effects on outer-scope variables during transaction retries.

    def update_albums(transaction: spanner_v1.Transaction) -> tuple[list[int], int]:
        results = transaction.execute_sql(
            "UPDATE Albums "
            "SET MarketingBudget = MarketingBudget * 2 "
            "WHERE SingerId = 1 AND AlbumId = 1 "
            "THEN RETURN MarketingBudget"
        )
        returned_budgets = [int(row[0] or 0) for row in results]
        return returned_budgets, int(results.stats.row_count_exact)

    try:
        budgets, row_count = database.run_in_transaction(update_albums)
    except exceptions.NotFound as err:
        print(
            f"error: database '{database_id}' on instance '{instance_id}' "
            f"in project '{project_id}' was not found: {err.message}",
            file=sys.stderr,
        )
    except exceptions.GoogleAPICallError as err:
        print(
            f"error: UPDATE DML RETURNING failed on database '{database_id}' "
            f"in instance '{instance_id}' for project '{project_id}': {err.message}",
            file=sys.stderr,
        )
    else:
        print(f"Resource ID: {database.name}")
        for budget in budgets:
            print(f"Marketing Budget: {budget}")
        print(f"Updated Rows: {row_count}")

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! This comment refers to an earlier revision of this file; the code here has since been reworked in later commits, so this thread no longer applies to the current diff.

Uses a nonlocal row counter with a defensive results.stats check and omits project identifiers from stdout and stderr.
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/dml/src/spanner_dml/update_dml_returning.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.

2 participants