Skip to content

feat(spanner): Add PostgreSQL bit-reversed sequence creation sample - #14939

Open
iennae wants to merge 3 commits into
feat/spanner-postgresql-dml-last-statementfrom
feat/spanner-postgresql-create-sequence
Open

iennae wants to merge 3 commits into
feat/spanner-postgresql-dml-last-statementfrom
feat/spanner-postgresql-create-sequence

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_postgresql_create_sequence creating a BIT_REVERSED_POSITIVE PostgreSQL sequence and inserting rows with RETURNING.

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

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

PostgreSQL-dialect primary keys avoid write hotspots using BIT_REVERSED_POSITIVE sequences with nextval('Seq') defaults. Add spanner_postgresql_create_sequence creating Seq and inserting Customers.
@iennae
iennae requested review from a team as code owners November 18, 2026 05:14
@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

@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

@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 script, postgresql_create_sequence.py, along with its corresponding tests, to demonstrate creating a bit-reversed PostgreSQL sequence and inserting rows using a RETURNING clause in Spanner. The feedback suggests splitting the DDL and DML operations into separate try-except blocks for more precise error handling and using standard exception handling for consistency. Additionally, it recommends returning the customer IDs directly from the transaction callback instead of using nonlocal state mutation to make the code more idiomatic.

Comment on lines +49 to +83
customer_ids: list[int] = []

def insert_customers(transaction: spanner_v1.transaction.Transaction) -> None:
nonlocal customer_ids
rows = list(
transaction.execute_sql(
"INSERT INTO Customers (CustomerName) VALUES "
"('Alice'), ('David'), ('Marc') "
"RETURNING CustomerId"
)
)
customer_ids = [int(row[0]) for row in rows]

try:
operation = admin_client.update_database_ddl(request=ddl_request)
print(f"Waiting for PostgreSQL sequence 'Seq' creation on '{database_id}'...")
operation.result(timeout=300)
database.run_in_transaction(insert_customers)
except (exceptions.AlreadyExists, exceptions.FailedPrecondition) as err:
print(
f"error: sequence 'Seq' or table 'Customers' already exists on "
f"database '{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to create PostgreSQL sequence on database "
f"'{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
else:
print(f"Resource ID: {database_id}")
for cid in customer_ids:
print(f"Customer ID: {cid}")
print(f"Inserted Customers: {len(customer_ids)}")

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

There are two main areas of improvement in this block:

  1. Misleading Error Handling: Currently, the try-except block wraps both the DDL sequence/table creation and the DML transaction. Splitting these into separate try-except blocks ensures precise error reporting. To maintain consistency with other code samples in this repository, we should use standard exception handling rather than introducing specific library exception classes like GoogleAPICallError.
  2. Idiomatic Transaction Callback: In Python's Spanner SDK, database.run_in_transaction returns the value returned by the callback function. Returning the list of IDs directly from insert_customers is more idiomatic and avoids the need for nonlocal state mutation.
    def insert_customers(transaction: spanner_v1.transaction.Transaction) -> list[int]:
        rows = list(
            transaction.execute_sql(
                "INSERT INTO Customers (CustomerName) VALUES "
                "('Alice'), ('David'), ('Marc') "
                "RETURNING CustomerId"
            )
        )
        return [int(row[0]) for row in rows]

    try:
        operation = admin_client.update_database_ddl(request=ddl_request)
        print(f"Waiting for PostgreSQL sequence 'Seq' creation on '{database_id}'...")
        operation.result(timeout=300)
    except Exception as err:
        print(
            f"error: failed to create PostgreSQL sequence on database "
            f"'{database_id}' in instance '{instance_id}': {err}",
            file=sys.stderr,
        )
        return

    try:
        customer_ids = database.run_in_transaction(insert_customers)
    except Exception as err:
        print(
            f"error: failed to insert customers on database "
            f"'{database_id}' in instance '{instance_id}': {err}",
            file=sys.stderr,
        )
        return

    print(f"Resource ID: {database_id}")
    for cid in customer_ids:
        print(f"Customer ID: {cid}")
    print(f"Inserted Customers: {len(customer_ids)}")
References
  1. For code samples, prioritize consistency with existing samples in the repository over introducing specific library exception classes (like 'google.api_core.exceptions.GoogleAPIError') if they are not already commonly used.

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! Keeping the current structure: the sample catches specific google.api_core.exceptions types so readers see concrete error handling, and the callback records its result in an enclosing variable for consistency with the rest of this sample set. A TimeoutError handler for the DDL wait was added separately (8935efe).

@amcolin amcolin 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.

Left some non-blocking suggestions.

import sys

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

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.

I believe this is a redundant import, we could just call the client like spanner_v1.Client(project=project_id)

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! I'm going to keep this one as is: the samples in this set consistently create the client through spanner.Client, which is the entry point used in the product documentation, and spanner_v1 is only imported here for the transaction callback's type annotation. Switching just this sample to spanner_v1.Client would make it the odd one out.

f"database '{database_id}' in instance '{instance_id}': {err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:

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.

Missing to handle Timeout error:

except TimeoutError as err:
        print(
            f"error: timed out waiting to drop PostgreSQL sequence "
            f"'{sequence_name}' on database '{database_id}' in instance "
            f"'{instance_id}': {err}",
            file=sys.stderr,
        )

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, thank you! Added an except TimeoutError handler and a unit test for it (8935efe). One note on the wording: the timeout only bounds how long the client waits and does not cancel the schema change, so the message says the wait timed out and that the operation may still be running.

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/postgresql/src/spanner_postgresql/postgresql_create_sequence.py
  - spanner/postgresql/tests/postgresql_create_sequence_test.py
…quence

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/postgresql/src/spanner_postgresql/postgresql_create_sequence.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