Skip to content

Commit

Permalink
Add missing contraint on annotation_metadata.annotation_id
Browse files Browse the repository at this point in the history
To avoid locking the table for a long time, the constraint is added in two steps:

- Add an unique index, concurrently
- Use that index as the base for the constraint
  • Loading branch information
marcospri committed Jan 20, 2025
1 parent 5cc8fb8 commit eb5bc0a
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions h/migrations/versions/78d3d6fe1d42_metadata_unique_constraint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Add missing unique constraint on annotation_medatada."""

import sqlalchemy as sa
from alembic import op

revision = "78d3d6fe1d42"
down_revision = "a122e276f8d1"


def upgrade():
conn = op.get_bind()

# CONCURRENTLY can't be used inside a transaction. Finish the current one.
op.execute("COMMIT;")

# First create the index concurrently to avoid locking the table
conn.execute(
sa.text(
"""
CREATE UNIQUE INDEX CONCURRENTLY ix__annotation_metadata__annotation_id ON annotation_metadata (annotation_id);
"""
)
)
# Once the index is created, use it to create the unique constraint
conn.execute(
sa.text(
"""
ALTER TABLE annotation_metadata ADD CONSTRAINT uq__annotation_metadata__annotation_id UNIQUE USING INDEX ix__annotation_metadata__annotation_id
"""
)
)


def downgrade():
op.drop_constraint(
op.f("uq__annotation_metadata__annotation_id"),
"annotation_metadata",
type_="unique",
)

0 comments on commit eb5bc0a

Please sign in to comment.