Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix docs for disallowed-unique-constraint #370

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/docs/disallowed-unique-constraint.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Use:
```sql
-- allows reads and writes while index is built
CREATE UNIQUE INDEX CONCURRENTLY dist_id_uniq ON distributors (dist_id);
-- add constraint using the built index
ALTER TABLE distributors ADD CONSTRAINT distributors_dist_id_key UNIQUE USING INDEX dist_id_uniq;
```


Expand All @@ -44,12 +46,15 @@ Use:
ALTER TABLE distributors ADD COLUMN dist_id text;
-- allows reads and writes while index is built
CREATE UNIQUE INDEX CONCURRENTLY dist_id_uniq ON distributors (dist_id);
-- add constraint using the built index
ALTER TABLE distributors ADD CONSTRAINT distributors_dist_id_key UNIQUE USING INDEX dist_id_uniq;
```

## solution for alembic and sqlalchemy

```python
# migrations/*.py
# First migration
from alembic import op

def schema_upgrades():
Expand All @@ -69,3 +74,29 @@ def schema_downgrades():
postgresql_concurrently=True,
)
```

```python
# migrations/*.py
# Second migration
from alembic import op
import sqlalchemy as sa

def schema_upgrades():
op.execute(
sa.text(
"""
ALTER TABLE distributors ADD CONSTRAINT distributors_dist_id_key UNIQUE USING INDEX dist_id_uniq;
"""
),
)

def schema_downgrades():
op.drop_constraint(
"distributors_dist_id_key",
type_="unique",
)
```

## links

- https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-DESC-ADD-TABLE-CONSTRAINT-USING-INDEX
Loading