Last active
January 11, 2024 22:34
-
-
Save kurtbrose/5cc2738d089c8ae9f1049d216a48651f to your computer and use it in GitHub Desktop.
Helper to reset the sequences on a postgres database before running CI to ensure that ids will be very different between tables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import select, text | |
def reset_sequences(engine, schema="public", gap=10000): | |
""" | |
Reset all sequences in a given schema to 10000, 20000, etc. so that ids won't overlap easily. | |
Ensures we don't get "lucky" and crossing ids between tables works because they are both id=1, | |
passing a test that should fail. | |
""" | |
with engine.connect() as conn: | |
# Get the list of all sequence names in the schema | |
query = ( | |
select(text("sequence_name")) | |
.select_from(text("information_schema.sequences")) | |
.where(text("sequence_schema = :schema")) | |
.offset(1) # we can skip the first table, it gets to start from 1 | |
) | |
sequence_names = conn.execute(query, schema=schema).scalars() | |
alter_sequence_statements = [ | |
f"ALTER SEQUENCE {sequence_name} RESTART WITH {1 + idx * gap}" | |
for idx, sequence_name in enumerate(sequence_names) | |
] | |
# Reset each sequence | |
conn.execute(text(";\n".join(alter_sequence_statements))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment