Opened 9 years ago
Closed 8 years ago
#26090 closed Bug (fixed)
Changing a ForeignKey to a OneToOne field leaves an extraneous index behind
Reported by: | Aymeric Augustin | Owned by: | nobody |
---|---|---|---|
Component: | Migrations | Version: | 1.9 |
Severity: | Normal | Keywords: | |
Cc: | jon.dufresne@… | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
(This happened to me on PostgreSQL, I don't know about other databases.)
Assume a Child model that has a foreign key to its a Parent. makemigrations
+ migrate
generate the following index:
CREATE INDEX app_child_<hash> ON app_child USING btree (parent_id);
If the foreign key is later turned into a one-to-one relationship, makemigrations
+ migrate
generates the following constraint:
ALTER TABLE ONLY app_child ADD CONSTRAINT app_child_parent_id_key UNIQUE (parent_id);
The original index remains.
However, if the parent relationship had been originally declared as a one-to-one, only the constraint would have been generated, not the index. (I noticed after recreating all migrations from scratch for performance reasons and comparing the database schema.)
I believe that:
- this falls within use cases where the migrations framework should keep the database state consistent
- the index is redundant with the constraint and should have been dropped in that case
See also the opposite case of
OneToOneField
toForeignKey
in #25317.