Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,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)
- Respect the root ``max_recursion`` limit when generating nested Pydantic models. (#2400)
- ``TextField(null=True)`` now narrows to ``TextField[str | None]`` instead of staying ``TextField[str]``. (#2218)
- docs: fix relation accessors in model and query examples. (#2411)
Expand Down
27 changes: 27 additions & 0 deletions tests/migrations/test_operations_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,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")
Expand Down
35 changes: 35 additions & 0 deletions tests/migrations/test_schema_editor_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
20 changes: 20 additions & 0 deletions tests/migrations/test_schema_editor_sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
3 changes: 2 additions & 1 deletion tests/migrations/test_state_diff_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
23 changes: 19 additions & 4 deletions tortoise/migrations/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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,
Expand All @@ -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):
Expand Down
4 changes: 4 additions & 0 deletions tortoise/migrations/schema_editor/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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],
Expand Down
3 changes: 3 additions & 0 deletions tortoise/migrations/schema_editor/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 2 additions & 9 deletions tortoise/migrations/schema_generator/state_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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)
Expand Down