fix(migration): use IF EXISTS when dropping chunk FK constraint (#725)
* fix(migration): use IF EXISTS when dropping chunk FK constraint The migration unconditionally dropped memory_units_chunk_fkey, but depending on the order in which migrations were applied the constraint may not exist. Use raw SQL with IF EXISTS so the drop is safe regardless. * fix(migration): make chunk FK add idempotent with DO block The previous fix only handled the DROP side with IF EXISTS. The ADD side could still fail with DuplicateObject when the FK already existed on a schema that was provisioned after the base migration ran. Wrap the ADD CONSTRAINT in a DO block to catch duplicate_object and continue, making the migration fully idempotent in both directions.
This commit is contained in:
parent
1ac80bda6f
commit
26e6877b53
1 changed files with 22 additions and 3 deletions
|
|
@ -24,9 +24,28 @@ def upgrade() -> None:
|
|||
the memory_units rows survived with chunk_id = NULL, leaving ghost records.
|
||||
Switching to CASCADE ensures they are removed together with their chunk.
|
||||
"""
|
||||
op.drop_constraint("memory_units_chunk_fkey", "memory_units", type_="foreignkey")
|
||||
op.create_foreign_key(
|
||||
"memory_units_chunk_fkey", "memory_units", "chunks", ["chunk_id"], ["chunk_id"], ondelete="CASCADE"
|
||||
from alembic import context
|
||||
|
||||
schema = context.config.get_main_option("target_schema")
|
||||
schema_prefix = f'"{schema}".' if schema else ""
|
||||
# Use raw SQL with IF EXISTS so this is safe on schemas where the FK was
|
||||
# already dropped or never existed under this name.
|
||||
op.execute(f"ALTER TABLE {schema_prefix}memory_units DROP CONSTRAINT IF EXISTS memory_units_chunk_fkey")
|
||||
# Use a DO block so the ADD is also idempotent: if the FK already exists (e.g.
|
||||
# the schema was provisioned after the base migration already added it) the
|
||||
# duplicate_object exception is swallowed rather than failing the migration.
|
||||
op.execute(
|
||||
f"""
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE {schema_prefix}memory_units
|
||||
ADD CONSTRAINT memory_units_chunk_fkey
|
||||
FOREIGN KEY (chunk_id)
|
||||
REFERENCES {schema_prefix}chunks (chunk_id)
|
||||
ON DELETE CASCADE;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue