Skip to content

feat(spanner): Add GoogleSQL ALTER SEQUENCE skip_range sample - #14955

Open
iennae wants to merge 2 commits into
feat/spanner-create-databasefrom
feat/spanner-alter-sequence
Open

iennae wants to merge 2 commits into
feat/spanner-create-databasefrom
feat/spanner-alter-sequence

Conversation

@iennae

@iennae iennae commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Description

Adds spanner_alter_sequence configuring skip_range_min and skip_range_max on a GoogleSQL bit-reversed sequence.

Note: Stacked on #14943 (feat/spanner-create-database) so this PR shows only this sample's diff. It will merge into main after #14943.

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

Migrating existing primary keys into a sequence-backed table skips reserved ID ranges via skip_range_min and skip_range_max. Add a standalone spanner_alter_sequence sample and test suite.
@iennae
iennae requested review from a team as code owners November 18, 2026 22:18
@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 adds functionality and tests for altering GoogleSQL sequences in Google Cloud Spanner. The review feedback identifies two key issues: first, in the live test's cleanup block, the Customers table must be dropped before the sequence is dropped to prevent a dependency violation; second, the main script's error handling should separate the sequence alteration and transaction execution to avoid misleading error messages if the customer insertion fails.

Comment on lines +161 to +172
finally:
drop_sequence.drop_sequence(
conftest.LIVE_PROJECT_ID,
conftest.LIVE_INSTANCE_ID,
conftest.LIVE_DATABASE_ID,
)
admin.update_database_ddl(
request={
"database": db_path,
"statements": ["DROP TABLE IF EXISTS Customers"],
}
).result(timeout=240)

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.

high

In Cloud Spanner, you cannot drop a sequence if it is still referenced by a table column's default value constraint. Since the Customers table references the Seq sequence, calling drop_sequence.drop_sequence before dropping the Customers table will fail with a FailedPrecondition error. The Customers table must be dropped first in the finally block.

Suggested change
finally:
drop_sequence.drop_sequence(
conftest.LIVE_PROJECT_ID,
conftest.LIVE_INSTANCE_ID,
conftest.LIVE_DATABASE_ID,
)
admin.update_database_ddl(
request={
"database": db_path,
"statements": ["DROP TABLE IF EXISTS Customers"],
}
).result(timeout=240)
finally:
admin.update_database_ddl(
request={
"database": db_path,
"statements": ["DROP TABLE IF EXISTS Customers"],
}
).result(timeout=240)
drop_sequence.drop_sequence(
conftest.LIVE_PROJECT_ID,
conftest.LIVE_INSTANCE_ID,
conftest.LIVE_DATABASE_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! The cleanup works in this order because the drop-sequence sample first removes the column default (ALTER TABLE Customers ALTER COLUMN CustomerId DROP DEFAULT) and then drops the sequence, so the table no longer references it.

Comment on lines +56 to +83
try:
operation = admin_client.update_database_ddl(request=ddl_request)
print(f"Waiting for sequence 'Seq' alteration on '{database_id}'...")
operation.result(timeout=300)
database.run_in_transaction(insert_customers)
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 TimeoutError as err:
print(
f"error: timed out waiting for the operation on database '{database_id}' "
f"to complete; the operation may still be running: {err}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: failed to alter sequence on database '{database_id}' "
f"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

If database.run_in_transaction(insert_customers) fails (for example, due to a schema mismatch or missing table), the current error handling will catch it and print a misleading error message stating that the sequence alteration failed. Splitting the sequence alteration and the customer insertion into separate try-except blocks provides clearer and more accurate error messages.

    try:
        operation = admin_client.update_database_ddl(request=ddl_request)
        print(f"Waiting for sequence 'Seq' alteration on '{database_id}'...")
        operation.result(timeout=300)
    except exceptions.NotFound as err:
        print(
            f"error: database '{database_id}' on instance '{instance_id}' "
            f"was not found: {err.message}",
            file=sys.stderr,
        )
        return
    except TimeoutError as err:
        print(
            f"error: timed out waiting for the operation on database '{database_id}' "
            f"to complete; the operation may still be running: {err}",
            file=sys.stderr,
        )
        return
    except exceptions.GoogleAPICallError as err:
        print(
            f"error: failed to alter sequence on database '{database_id}' "
            f"in instance '{instance_id}': {err.message}",
            file=sys.stderr,
        )
        return

    try:
        database.run_in_transaction(insert_customers)
    except exceptions.GoogleAPICallError as err:
        print(
            f"error: failed to insert customers into database '{database_id}': {err.message}",
            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)}")

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 a single block here for consistency with the other samples in this set; the error message includes the server message, which identifies the step that failed.

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/database_admin/src/spanner_database_admin/alter_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.

1 participant