Skip to content

feat(spanner): Add GoogleSQL INSERT DML THEN RETURN sample - #14860

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

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

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Using INSERT ... THEN RETURN reads server-generated columns such as FullName in the same round trip as the insert without issuing a follow-up SELECT.

Adds spanner_insert_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 generated columns from inserted rows in a single round trip uses INSERT ... THEN RETURN, aligning Python with the canonical region tag shared across peer languages.
@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 Python script and corresponding tests to demonstrate the use of Spanner's 'INSERT ... THEN RETURN' DML statement. The review feedback suggests a more idiomatic and robust approach for handling transaction results: returning the inserted names and row count directly from the transaction callback function instead of mutating lists in the outer scope, which avoids potential side effects during transaction retries.

Comment on lines +33 to +70
inserted_names: list[str] = []
row_counts: list[int] = []

def insert_singers(transaction: spanner_v1.Transaction) -> None:
inserted_names.clear()
row_counts.clear()
results = transaction.execute_sql(
"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES "
"(21, 'Luann', 'Chizoba'), "
"(22, 'Denis', 'Patricio'), "
"(23, 'Felix', 'Ronan'), "
"(24, 'Dominik', 'Martyna') "
"THEN RETURN FullName"
)
for row in results:
inserted_names.append(str(row[0]))
row_counts.append(int(results.stats.row_count_exact))

try:
database.run_in_transaction(insert_singers)
except exceptions.AlreadyExists as err:
print(
f"error: one or more SingerId rows already exist in database "
f"'{database_id}' on instance '{instance_id}' in project "
f"'{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: INSERT 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 full_name in inserted_names:
print(f"Full Name: {full_name}")
print(f"Inserted 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

Instead of defining and mutating list variables (inserted_names and row_counts) in the outer scope of the transaction function, it is more idiomatic and robust to return the results directly from the transaction function. The database.run_in_transaction method returns the value returned by the callback function. This approach avoids side effects during transaction retries and simplifies the code by using a list comprehension.

    def insert_singers(transaction: spanner_v1.Transaction) -> tuple[list[str], int]:
        results = transaction.execute_sql(
            "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES "
            "(21, 'Luann', 'Chizoba'), "
            "(22, 'Denis', 'Patricio'), "
            "(23, 'Felix', 'Ronan'), "
            "(24, 'Dominik', 'Martyna') "
            "THEN RETURN FullName"
        )
        inserted_names = [str(row[0]) for row in results]
        row_count = results.stats.row_count_exact if results.stats else 0
        return inserted_names, row_count

    try:
        inserted_names, row_count = database.run_in_transaction(insert_singers)
    except exceptions.AlreadyExists as err:
        print(
            f"error: one or more SingerId rows already exist in database "
            f"'{database_id}' on instance '{instance_id}' in project "
            f"'{project_id}': {err.message}",
            file=sys.stderr,
        )
    except exceptions.GoogleAPICallError as err:
        print(
            f"error: INSERT 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 full_name in inserted_names:
            print(f"Full Name: {full_name}")
        print(f"Inserted 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/insert_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