Skip to content

Commit 03f3063

Browse files
committed
fix error on altering char field with index to foreign key
1 parent 2244f93 commit 03f3063

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

sql_server/pyodbc/schema.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,12 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
189189
# True | False | False | False
190190
# True | False | False | True
191191
# True | False | True | True
192-
if old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique):
192+
if (old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique)) or (
193+
# Drop indexes on nvarchar columns that are changing to a different type
194+
# SQL Server requires explicit deletion
195+
(old_field.db_index or old_field.unique) and (
196+
(old_type.startswith('nvarchar') and not new_type.startswith('nvarchar'))
197+
)):
193198
# Find the index for this field
194199
meta_index_names = {index.name for index in model._meta.indexes}
195200
# Retrieve only BTREE indexes since this is what's created with
@@ -322,7 +327,9 @@ def _alter_field(self, model, old_field, new_field, old_type, new_type,
322327
if (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique:
323328
self.execute(self._create_index_sql(model, [new_field]))
324329
# Restore an index, SQL Server requires explicit restoration
325-
if old_type != new_type or (old_field.null and not new_field.null):
330+
if (old_type != new_type or (old_field.null and not new_field.null)) and (
331+
old_field.column == new_field.column
332+
):
326333
unique_columns = []
327334
if old_field.unique and new_field.unique:
328335
unique_columns.append([old_field.column])

0 commit comments

Comments
 (0)