Opened 3 years ago

Closed 3 years ago

#33125 closed Cleanup/optimization (fixed)

Changing model field to become PK creates redundant UNIQUE constraint

Reported by: Fabio Sangiovanni Owned by: Jordan Bae
Component: Migrations Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,

when swapping the primary_key=True attribute between two model fields, migrations.AlterField seems to generate a redundant UNIQUE constraint involving the new PK field.

To reproduce:

Prerequisites:

PostgreSQL 11.12
Python 3.8
Django main@7d909b2282c91c5bc5204dd160412e90fa86d624

Before state:

class Pony(models.Model):
    name = models.CharField(max_length=32, primary_key=True)
    nickname = models.CharField(max_length=32)

sqlmigrate:

BEGIN;
--
-- Create model Pony
--
CREATE TABLE "app_pony" ("name" varchar(32) NOT NULL PRIMARY KEY, "nickname" varchar(32) NOT NULL);
CREATE INDEX "app_pony_name_204da2d2_like" ON "app_pony" ("name" varchar_pattern_ops);
COMMIT;

After state:

class Pony(models.Model):
    name = models.CharField(max_length=32)
    nickname = models.CharField(max_length=32, primary_key=True)

sqlmigrate:

BEGIN;
--
-- Alter field name on pony
--
DROP INDEX IF EXISTS "app_pony_name_204da2d2_like";
--
-- Alter field nickname on pony
--
ALTER TABLE "app_pony" ADD CONSTRAINT "app_pony_nickname_1b2a0f82_uniq" UNIQUE ("nickname");
ALTER TABLE "app_pony" ADD CONSTRAINT "app_pony_nickname_1b2a0f82_pk" PRIMARY KEY ("nickname");
CREATE INDEX "app_pony_nickname_1b2a0f82_like" ON "app_pony" ("nickname" varchar_pattern_ops);
COMMIT;

The app_pony_nickname_1b2a0f82_uniq constraint looks reduntant to me, since the nickname field is going to become PK anyways.

Please let me know if I'm missing something or if I can be of further help.

Thanks,

Fabio

Change History (7)

comment:1 by Mariusz Felisiak, 3 years ago

Triage Stage: UnreviewedAccepted
Type: BugCleanup/optimization

Thanks for the report. We can probably add the same behavior as in #29496 (see 6dd4edb1b4f5441c5f543e29395039839c50d10b) on Oracle to other backends.

comment:2 by Jordan Bae, 3 years ago

Owner: changed from nobody to Jordan Bae
Status: newassigned

I will make PR for this.

comment:3 by Jordan Bae, 3 years ago

Has patch: set

comment:4 by Mariusz Felisiak, 3 years ago

Needs tests: set
Patch needs improvement: set

comment:5 by Jordan Bae, 3 years ago

Needs tests: unset
Patch needs improvement: unset

Thank you for reviewing! I updated the code :)

comment:6 by Mariusz Felisiak, 3 years ago

Triage Stage: AcceptedReady for checkin

comment:7 by Mariusz Felisiak <felisiak.mariusz@…>, 3 years ago

Resolution: fixed
Status: assignedclosed

In f5a32439:

Fixed #33125 -- Avoided redundant unique constraint when converting a non-unique field to primary key on MySQL and PostgreSQL.

Note: See TracTickets for help on using tickets.
Back to Top