Description
Problem
When doing migrations.RenameField
on a field which is a models.ManyToManyField
, the filtered UNIQUE INDEX
(which enforces the uniqueness constraint on A_ID,B_ID pairs on the through table) is dropped before the rename, but not re-instated afterwards ⚠
Example
So I see something like this:
DROP INDEX myapp_mymodel_fieldname_x_id_y_id_uniq ON myapp_mymodel_fieldname
EXEC sp_rename [myapp_mymodel_fieldname], [myapp_mymodel_newfieldname]
and aftewards the dropped index is missing.
The lost index is the one created earlier (when the m2m field was added) to enforce the unique_together
constraint on the 2 ID fields (on the through model which create_many_to_many_intermediary_model
generates) something like this:
CREATE UNIQUE INDEX [myapp_mymodel_fieldname_x_id_y_id_uniq ] ON [myapp_mymodel_fieldname] ([x_id], [y_id]) WHERE [x_id] IS NOT NULL AND [y_id] IS NOT NULL
Cause
This seems to be the code at fault: https://github.com/microsoft/mssql-django/blame/1.1.1/mssql/schema.py#L231-L232 which came in ESSolutions/django-mssql-backend#24 where unique_together
was first changed to be implemented by a filtered-unique-index rather than a constraint (in order to support nullability).
Test
I've written a regression test which fails due to the above bug: #88