|
| 1 | +"""Fix linked_production_pdl_id foreign key to SET NULL on delete |
| 2 | +
|
| 3 | +Revision ID: 005 |
| 4 | +Revises: 004 |
| 5 | +Create Date: 2025-12-11 01:00:00 |
| 6 | +
|
| 7 | +Fixes IntegrityError when deleting a PDL that is referenced by another PDL |
| 8 | +via linked_production_pdl_id. The FK constraint now uses ON DELETE SET NULL |
| 9 | +so that deleting a production PDL automatically nullifies the reference |
| 10 | +in any consumption PDL that was linked to it. |
| 11 | +""" |
| 12 | +from typing import Sequence, Union |
| 13 | + |
| 14 | +from alembic import op |
| 15 | + |
| 16 | + |
| 17 | +# revision identifiers, used by Alembic. |
| 18 | +revision: str = "005" |
| 19 | +down_revision: Union[str, None] = "004" |
| 20 | +branch_labels: Union[str, Sequence[str], None] = None |
| 21 | +depends_on: Union[str, Sequence[str], None] = None |
| 22 | + |
| 23 | + |
| 24 | +def upgrade() -> None: |
| 25 | + bind = op.get_bind() |
| 26 | + dialect = bind.dialect.name |
| 27 | + |
| 28 | + if dialect == "postgresql": |
| 29 | + # PostgreSQL - drop and recreate the FK constraint with ON DELETE SET NULL |
| 30 | + op.execute(""" |
| 31 | + ALTER TABLE pdls |
| 32 | + DROP CONSTRAINT IF EXISTS pdls_linked_production_pdl_id_fkey |
| 33 | + """) |
| 34 | + op.execute(""" |
| 35 | + ALTER TABLE pdls |
| 36 | + ADD CONSTRAINT pdls_linked_production_pdl_id_fkey |
| 37 | + FOREIGN KEY (linked_production_pdl_id) REFERENCES pdls(id) |
| 38 | + ON DELETE SET NULL |
| 39 | + """) |
| 40 | + else: |
| 41 | + # SQLite doesn't support ALTER CONSTRAINT, but it also doesn't |
| 42 | + # enforce foreign keys by default, so this is a no-op for SQLite. |
| 43 | + # If you need strict FK enforcement in SQLite, you'd need to |
| 44 | + # recreate the table entirely. |
| 45 | + pass |
| 46 | + |
| 47 | + |
| 48 | +def downgrade() -> None: |
| 49 | + bind = op.get_bind() |
| 50 | + dialect = bind.dialect.name |
| 51 | + |
| 52 | + if dialect == "postgresql": |
| 53 | + # Restore the original FK constraint without ON DELETE behavior |
| 54 | + op.execute(""" |
| 55 | + ALTER TABLE pdls |
| 56 | + DROP CONSTRAINT IF EXISTS pdls_linked_production_pdl_id_fkey |
| 57 | + """) |
| 58 | + op.execute(""" |
| 59 | + ALTER TABLE pdls |
| 60 | + ADD CONSTRAINT pdls_linked_production_pdl_id_fkey |
| 61 | + FOREIGN KEY (linked_production_pdl_id) REFERENCES pdls(id) |
| 62 | + """) |
| 63 | + else: |
| 64 | + pass |
0 commit comments