Skip to content

AlterField fails if unique_together created by old backend #137

@sparrowt

Description

@sparrowt

Problem steps

  • have a database created & migrated using an older version of this backend (django-pyodbc-azure & django-mssql-backend < v2.6.0) which implements unique_together with a table CONSTRAINT
  • start using a newer version of the backend code which implements unique_together using a filtered unique INDEX instead
  • add a migration which does AlterField to change the type/nullability of a field which is contained within a unique_together
  • it explodes with something like:
django.db.utils.ProgrammingError: ('42S11', "[42S11] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The operation failed because an index or statistics with name 'appname_tablename_fielda_fieldb_deadbeef_uniq' already exists on table 'appname_tablename'. (1913) (SQLExecDirectW)")

Cause

This happens because:

  • in _alter_field, before changing the type/nullability it drops certain constraints/indexes but it isn't expecting there to be a CONSTRAINT implementing a unique_together (because that's not what it would have created)
  • so it doesn't look for & delete this, meaning that it's still in place
  • then the field is modified (which, interestingly doesn't fail - so I guess the removal of the unique_together constraint may not be strictly required for all cases - but that's not such a big deal)
  • then _alter_field tries to reinstate the unique_together, but that fails because something with that name already exists (although it's a constraint, but under the hood I believe MSSQL is implementing that CONSTRAINT with an INDEX anyway...!)

This is related to #104 but isn't fixed by #106 (which covers other cases excellently, just not this one).

I have a local patch & regression test on the way...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions