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 @@ -55,6 +55,7 @@ Fixed
- ``migrate``/``plan``/``sqlmigrate`` on a subset of apps now load dependency apps' migrations, so cross-app ``ForeignKeyField`` columns and constraints are no longer silently omitted. (#2278)
- ``values_list(..., flat=True)`` is typed as a list of values (or a single value after ``.get()`` / ``.first()``) instead of tuples. (#2421)
- Model instances without a primary key now compare equal only to themselves, so two distinct unsaved instances are no longer equal. (#2420)
- ``select_related()`` no longer drops related fields on PostgreSQL when ``"<table>.<column>"`` is longer than 63 bytes, which left the related instance partial so ``save()`` raised ``IncompleteInstanceError``. (#2395)

1.1.9
-----
Expand Down
18 changes: 18 additions & 0 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Event,
Extra,
M2mWithO2oPk,
ModelWithATableNameLongEnoughToHitIdentifierLimits,
Node,
O2oPkModelWithM2m,
Pair,
Expand Down Expand Up @@ -403,6 +404,23 @@ async def test_select_related_sets_valid_nulls(db) -> None:
assert retrieved_root.left.left == left_2nd_lvl


@pytest.mark.asyncio
async def test_select_related_with_long_table_name(db) -> None:
model = ModelWithATableNameLongEnoughToHitIdentifierLimits
parent = await model.create(title="parent")
child = await model.create(title="child", parent=parent)

fetched = await model.filter(pk=child.pk).select_related("parent").get()
assert fetched.parent is not None
assert fetched.parent.pk == parent.pk
assert fetched.parent.title == "parent"
assert fetched.parent.parent_id is None

fetched.parent.title = "renamed"
await fetched.parent.save()
assert (await model.get(pk=parent.pk)).title == "renamed"


@pytest.mark.asyncio
async def test_no_ambiguous_fk_relations_set(db):
"""Basic select_related test cases provided by @https://github.com/Terrance.
Expand Down
14 changes: 14 additions & 0 deletions tests/testmodels.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,20 @@ class DoubleFK(Model):
)


class ModelWithATableNameLongEnoughToHitIdentifierLimits(Model):
# "<table>__parent.title" is longer than PostgreSQL's 63-byte identifier limit
title = fields.CharField(max_length=50)
parent: fields.ForeignKeyNullableRelation[
"ModelWithATableNameLongEnoughToHitIdentifierLimits"
] = fields.ForeignKeyField(
"models.ModelWithATableNameLongEnoughToHitIdentifierLimits",
null=True,
related_name="children",
on_delete=NO_ACTION,
)
parent_id: int | None


class DefaultOrdered(Model):
one = fields.TextField()
second = fields.IntField()
Expand Down
13 changes: 11 additions & 2 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,12 @@ def using_db(self, _db: BaseDBAsyncClient | None) -> QuerySet[MODEL]:
queryset._db = _db if _db else queryset._db
return queryset

def _related_column_alias(self, table: Table, field: str) -> str:
# The executor only reads the part after the first ".", so the prefix just has to be
# unique per joined table. "<table name>." could exceed identifier limits (63 bytes in
# PostgreSQL), and a truncated alias lost the field.
return f"{self._joined_tables.index(table)}.{field}"

def _join_select_related(self, lookup_expression: str) -> tuple[type[Model], Table]:
fields = expand_lookup_expression(self.model, lookup_expression)
model = self.model
Expand Down Expand Up @@ -1215,7 +1221,7 @@ def _join_select_related(self, lookup_expression: str) -> tuple[type[Model], Tab
self._select_related_idx.append(append_item)
self.query = self.query.select(
*[
table[related_field].as_(f"{table.get_table_name()}.{related_field}")
table[related_field].as_(self._related_column_alias(table, related_field))
for related_field in related_fields
]
)
Expand Down Expand Up @@ -1303,7 +1309,10 @@ def _resolve_only(self, only_lookup_expressions: tuple[str, ...]) -> None:
)
added_paths.add(path)
self.query = self.query.select(
*[table[field].as_(f"{table.get_table_name()}.{field}") for field in data_fields]
*[
table[field].as_(self._related_column_alias(table, field))
for field in data_fields
]
)

def _make_query(self) -> None:
Expand Down