From 790e0224add67d71056917aacf5205b3359ecce4 Mon Sep 17 00:00:00 2001 From: nk-batman21 Date: Mon, 26 Oct 2026 23:35:46 +0700 Subject: [PATCH] fix(migrations): create index for fields added with db_index=True AddField only emitted ALTER TABLE ... ADD COLUMN, so a field added to an existing model with db_index=True never got its index, while CreateModel and AlterField both create it. add_field now calls add_index after adding the column, as _alter_field does. A plain single-column index on a db_index field has the same name as the field's own index, so AddIndex and RemoveIndex now skip it, the way CreateModel already merges the two. Existing migrations that pair such an AddField with an AddIndex on the same column keep applying on a fresh database. The generated-field recreate path no longer emits its own AddIndex for the field, since AddField now creates that index. --- CHANGELOG.rst | 1 + tests/migrations/test_operations_database.py | 27 ++++++++++++++ tests/migrations/test_schema_editor_sql.py | 35 +++++++++++++++++++ tests/migrations/test_schema_editor_sqlite.py | 20 +++++++++++ .../migrations/test_state_diff_operations.py | 3 +- tortoise/migrations/operations.py | 23 +++++++++--- tortoise/migrations/schema_editor/base.py | 4 +++ tortoise/migrations/schema_editor/sqlite.py | 3 ++ .../migrations/schema_generator/state_diff.py | 11 ++---- 9 files changed, 113 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 21bc0d2a8..737a8fd19 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -38,6 +38,7 @@ Fixed - Parse false boolean values in database URL options correctly. (#2377) - Reject domain names with trailing newlines in ``DomainNameValidator``. (#2386) - ``QuerySet.exists()`` now respects ``limit()`` and ``offset()``, so ``limit(0)`` or an offset past the last row returns ``False``. (#2389) +- Migrations now create the index for fields added with ``db_index=True``; ``AddField`` previously only added the column. (#2384) 1.1.9 ----- diff --git a/tests/migrations/test_operations_database.py b/tests/migrations/test_operations_database.py index 4251b879f..9f19b88f1 100644 --- a/tests/migrations/test_operations_database.py +++ b/tests/migrations/test_operations_database.py @@ -159,6 +159,33 @@ async def test_remove_index_operation_runs_sql() -> None: assert client.executed[0] == 'DROP INDEX "idx_widget_id"' +@pytest.mark.asyncio +async def test_index_operations_skip_index_of_db_index_field() -> None: + client = FakeClient("sql") + editor = TestSchemaEditor(client) + state = State(models={}, apps=StateApps()) + CreateModel(name="Widget", fields=[("id", fields.IntField(pk=True))]).state_forward( + "models", state + ) + operations = [ + AddField( + model_name="Widget", name="name", field=fields.CharField(max_length=50, db_index=True) + ), + AddIndex(model_name="Widget", index=Index(fields=("name",))), + RemoveIndex(model_name="Widget", fields=["name"]), + AddIndex(model_name="Widget", index=Index(fields=("name",), name="widget_name")), + ] + + for op in operations: + await op.run("models", state, dry_run=False, state_editor=editor) + + assert client.executed == [ + 'ALTER TABLE "widget" ADD COLUMN "name" VARCHAR(50) NOT NULL', + 'CREATE INDEX "idx_widget_name_3fdd43" ON "widget" ("name");', + 'CREATE INDEX "widget_name" ON "widget" ("name");', + ] + + @pytest.mark.asyncio async def test_rename_index_operation_runs_sql() -> None: client = FakeClient("sql") diff --git a/tests/migrations/test_schema_editor_sql.py b/tests/migrations/test_schema_editor_sql.py index 73d51c863..6f0245775 100644 --- a/tests/migrations/test_schema_editor_sql.py +++ b/tests/migrations/test_schema_editor_sql.py @@ -68,6 +68,41 @@ async def test_add_field_generates_add_column_sql() -> None: assert '"name" TEXT' in sql +@pytest.mark.asyncio +async def test_add_field_with_db_index_creates_index() -> None: + class Author(Model): + id = fields.IntField(primary_key=True) + + class Meta: + table = "author" + app = "models" + + class Book(Model): + id = fields.IntField(primary_key=True) + isbn = fields.CharField(max_length=20, db_index=True) + author: fields.ForeignKeyRelation[Author] = fields.ForeignKeyField( + "models.Author", related_name="books", source_field="writer_id", db_index=True + ) + + class Meta: + table = "book" + app = "models" + + init_apps(Author, Book) + + client = FakeClient("sql") + editor = TestSchemaEditor(client) + + await editor.add_field(Book, "isbn") + await editor.add_field(Book, "author") + + assert len(client.executed) == 4 + assert 'ALTER TABLE "book" ADD COLUMN "isbn"' in client.executed[0] + assert client.executed[1] == editor._get_index_sql(Book, ["isbn"]) + assert 'ALTER TABLE "book" ADD COLUMN "writer_id"' in client.executed[2] + assert client.executed[3] == editor._get_index_sql(Book, ["writer_id"]) + + @pytest.mark.asyncio async def test_remove_field_generates_drop_column_sql() -> None: client = FakeClient("sql") diff --git a/tests/migrations/test_schema_editor_sqlite.py b/tests/migrations/test_schema_editor_sqlite.py index d5ded7e58..e88f540eb 100644 --- a/tests/migrations/test_schema_editor_sqlite.py +++ b/tests/migrations/test_schema_editor_sqlite.py @@ -34,6 +34,26 @@ async def test_sqlite_add_field_unique_uses_index() -> None: assert '"slug"' in unique_index_sql +@pytest.mark.asyncio +async def test_sqlite_add_field_db_index_creates_index() -> None: + class Article(Model): + id = fields.IntField(primary_key=True) + title = fields.CharField(max_length=50, db_index=True) + + class Meta: + table = "article" + app = "models" + + client = FakeClient("sqlite") + editor = SqliteSchemaEditor(client) + + await editor.add_field(Article, "title") + + assert len(client.executed) == 2 + assert 'ALTER TABLE "article" ADD COLUMN "title"' in client.executed[0] + assert client.executed[1] == editor._get_index_sql(Article, ["title"]) + + @pytest.mark.asyncio async def test_sqlite_constraint_name_used_for_drop() -> None: client = FakeClient("sqlite") diff --git a/tests/migrations/test_state_diff_operations.py b/tests/migrations/test_state_diff_operations.py index 6bdc44241..9f36e6e99 100644 --- a/tests/migrations/test_state_diff_operations.py +++ b/tests/migrations/test_state_diff_operations.py @@ -216,7 +216,8 @@ def test_generate_recreate_generated_field_restores_indexes_constraints() -> Non operations = OperationGenerator(old_state, new_state).generate() assert any(isinstance(op, RemoveField) for op in operations) assert any(isinstance(op, AddField) for op in operations) - assert any(isinstance(op, AddIndex) and op.index.INDEX_TYPE == "GIN" for op in operations) + # AddField recreates the db_index index itself, so only the GIN index is re-added + assert [op.index.INDEX_TYPE for op in operations if isinstance(op, AddIndex)] == ["GIN"] assert any( isinstance(op, AddConstraint) and isinstance(op.constraint, UniqueConstraint) diff --git a/tortoise/migrations/operations.py b/tortoise/migrations/operations.py index be158ee9b..473746539 100644 --- a/tortoise/migrations/operations.py +++ b/tortoise/migrations/operations.py @@ -654,6 +654,17 @@ def _set_option_list(model_state: ModelState, key: str, values: list) -> None: model_state.options.pop(key, None) +def _is_field_db_index(model: type[Model], index: Index) -> bool: + # A plain unnamed single-column Index is the one db_index=True already creates + if type(index) is not Index or index.name or index.expressions or len(index.fields) != 1: + return False + for field_name, db_field in model._meta.fields_db_projection.items(): + if db_field == index.fields[0]: + field = model._meta.fields_map[field_name] + return field.index and not field.pk + return False + + class AddIndex(TortoiseOperation): def __init__(self, model_name: str, index: Index) -> None: self.model_name = model_name @@ -679,7 +690,8 @@ async def database_forward( if not state_editor: return model = new_state.apps.get_model(f"{app_label}.{self.model_name}") - await state_editor.add_index(model, self.index) + if not _is_field_db_index(model, self.index): + await state_editor.add_index(model, self.index) async def database_backward( self, @@ -691,7 +703,8 @@ async def database_backward( if not state_editor: return model = old_state.apps.get_model(f"{app_label}.{self.model_name}") - await state_editor.remove_index(model, self.index) + if not _is_field_db_index(model, self.index): + await state_editor.remove_index(model, self.index) class RemoveIndex(TortoiseOperation): @@ -743,7 +756,8 @@ async def database_forward( model = old_state.apps.get_model(f"{app_label}.{self.model_name}") model_state = old_state.models[(app_label, self.model_name)] index = self._find_index(model_state) - await state_editor.remove_index(model, index) + if not _is_field_db_index(model, index): + await state_editor.remove_index(model, index) async def database_backward( self, @@ -757,7 +771,8 @@ async def database_backward( model = new_state.apps.get_model(f"{app_label}.{self.model_name}") model_state = new_state.models[(app_label, self.model_name)] index = self._find_index(model_state) - await state_editor.add_index(model, index) + if not _is_field_db_index(model, index): + await state_editor.add_index(model, index) class RenameIndex(TortoiseOperation): diff --git a/tortoise/migrations/schema_editor/base.py b/tortoise/migrations/schema_editor/base.py index d66ca4cd4..2b534c30b 100644 --- a/tortoise/migrations/schema_editor/base.py +++ b/tortoise/migrations/schema_editor/base.py @@ -521,6 +521,7 @@ async def add_field(self, model: type[Model], field_name: str) -> None: if isinstance(field, ForeignKeyFieldInstance): key_field_name = field.source_field or field_name + db_field = model._meta.fields_db_projection[key_field_name] field_definition = self._get_fk_field_definition(model, key_field_name) else: db_field = model._meta.fields_db_projection[field_name] @@ -567,6 +568,9 @@ async def add_field(self, model: type[Model], field_name: str) -> None: ) ) + if field.index and not field.pk: + await self.add_index(model, Index(fields=(db_field,))) + async def _alter_m2m_field( self, model: type[Model], diff --git a/tortoise/migrations/schema_editor/sqlite.py b/tortoise/migrations/schema_editor/sqlite.py index 318598c59..e75035e8e 100644 --- a/tortoise/migrations/schema_editor/sqlite.py +++ b/tortoise/migrations/schema_editor/sqlite.py @@ -141,6 +141,9 @@ async def add_field(self, model, field_name: str) -> None: if unique_field: await self.add_constraint(model, UniqueConstraint(fields=(db_field,))) + if field.index and not field.pk: + await self.add_index(model, Index(fields=(db_field,))) + async def add_constraint(self, model, constraint) -> None: from tortoise.migrations.constraints import CheckConstraint diff --git a/tortoise/migrations/schema_generator/state_diff.py b/tortoise/migrations/schema_generator/state_diff.py index db0a9ab4e..9a5470837 100644 --- a/tortoise/migrations/schema_generator/state_diff.py +++ b/tortoise/migrations/schema_generator/state_diff.py @@ -318,15 +318,8 @@ def __init__(self, old_state: ModelState, new_state: ModelState) -> None: self.old_state = old_state self.new_state = new_state - def _generated_field_recreate_ops( - self, field_name: str, field: Field - ) -> list[TortoiseOperation]: + def _generated_field_recreate_ops(self, field_name: str) -> list[TortoiseOperation]: operations: list[TortoiseOperation] = [] - if getattr(field, "index", False): - operations.append( - AddIndex(model_name=self.new_state.name, index=Index(fields=(field_name,))) - ) - old_indexes = _normalize_indexes(self.old_state.options.get("indexes", ())) new_indexes = _normalize_indexes(self.new_state.options.get("indexes", ())) old_index_sigs = {_index_signature(index) for index in old_indexes} @@ -398,7 +391,7 @@ def generate_operations(self) -> list[TortoiseOperation]: operations.append( AddField(model_name=self.new_state.name, name=name, field=new_field) ) - operations.extend(self._generated_field_recreate_ops(name, new_field)) + operations.extend(self._generated_field_recreate_ops(name)) else: operations.append( AlterField(model_name=self.new_state.name, name=name, field=new_field)