django / django/new-features

Allow unique indexes (via `UniqueConstraint`) to be created/dropped `CONCURRENTLY` on PostgreSQL

Open
#124 6 comments 29 reactions 0 assignees View on GitHub
Migrations
Dominant language
No language data
Stars
188
Forks
7
PR merge metrics
No merged PRs in 30d

Description

### Code of Conduct

- [x] I agree to follow Django's Code of Conduct

### Feature Description

A new pair of `contrib.postgres` operations to allow adding and dropping unique indexes using PostgreSQL's `CONCURRENTLY` option.

### Problem

Django supports unique constraints via `UniqueConstraint`s in a model’s `Meta.constraints`. Some of these constraints are implemented as unique indexes using `CREATE UNIQUE INDEX`, and can make use of the `CONCURRENTLY` option to avoid locking the table.

Currently, only `Index` objects in `Meta.indexes` can use `AddIndexConcurrently` and `RemoveIndexConcurrently`. Unique constraints in `Meta.constraints` do not have an equivalent mechanism, even when they are indexes behind the hood and could safely support `CONCURRENTLY`.

### Request or proposal

proposal

### Additional Details

Not all `UniqueConstraint`s are implemented as indexes. Constraints defining `fields`, and none of `includes`, `condition`, or `opclasses` use `ALTER TABLE ... ADD CONSTRAINT` ([source](https://github.com/django/django/blob/e84dc8715e91d51364ba6bda2b2fb07e7a8b750e/django/db/backends/base/schema.py#L1913-L1916)) while the unique constraints defining `expressions` or any of `includes`, `condition`, `opclasses` use `CREATE UNIQUE INDEX`.

The `CONCURRENTLY` option only applies to constraints backed by `CREATE UNIQUE INDEX`.

### Implementation Suggestions

Introduce `AddConstraintConcurrently` and `RemoveConstraintConcurrently`:

- If a `UniqueConstraint` is implemented via `CREATE UNIQUE INDEX`, these operations add the `CONCURRENTLY` keyword.
- Otherwise, they behave like the standard `AddConstraint` and `RemoveConstraint`.

A [proof of concept PR](https://github.com/cliffordgama/django/pull/1) demonstrates feasibility.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.