-
Notifications
You must be signed in to change notification settings - Fork 432
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add missing contraint on annotation_metadata.annotation_id
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
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
h/migrations/versions/78d3d6fe1d42_metadata_unique_constraint.py
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
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", | ||
) |