Repository navigation
Conversation
Postgres truncates identifiers to 63 bytes, which breaks parsing field names from long JOIN aliases in execute_select. Record each related group's field names when the query is built and zip them positionally so long OneToOne and nested FK names work. Fixes tortoise#1902 Co-authored-by: MarkGus0 <MarkGus0@users.noreply.github.com>
Merging this PR will improve performance by 33.44%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_hydrate_100_rows_many_fields |
17.1 ms | 12.8 ms | +33.44% |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing vyrnsynx:fix/postgres-long-join-alias-1902 (a211f78) with develop (ffc946e)
Nested lookups re-selected the parent relation columns while _select_related_idx kept a single entry, so positional hydration mis-sliced rows and set phantom related objects.
…g-join-alias-1902
…g-join-alias-1902
…g-join-alias-1902
|
Disclosure first: I have a different attempt at the same truncation in #2395 (short aliases instead of positional hydration; it started from #2018). I ran both branches against each other's cases, and one result on this branch seems worth reporting here in any case. On f8d1af4 with the psycopg backend (psycopg 3.3.6, PostgreSQL 16, CPython 3.13.1), hydration goes wrong when two selected columns of one related model get the same alias after truncation. The same code passes with asyncpg. The models from #1902 show it once import os
import uuid
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model
class Author(Model):
id = fields.UUIDField(primary_key=True, default=uuid.uuid4)
name = fields.CharField(max_length=100)
email = fields.CharField(max_length=100)
bio = fields.TextField()
class Book(Model):
id = fields.UUIDField(primary_key=True, default=uuid.uuid4)
author_model_relation_with_long_name = fields.ForeignKeyField("models.Author")
class Chapter(Model):
id = fields.UUIDField(primary_key=True, default=uuid.uuid4)
book_model_relation_with_long_name = fields.ForeignKeyField("models.Book")
async def main():
await Tortoise.init(db_url=os.environ["DB_URL"], modules={"models": ["__main__"]})
await Tortoise.generate_schemas()
author = await Author.create(name="A-name", email="a@example.test", bio="A-bio")
book = await Book.create(author_model_relation_with_long_name=author)
chapter = await Chapter.create(book_model_relation_with_long_name=book)
loaded = await Chapter.all().select_related(
"book_model_relation_with_long_name",
"book_model_relation_with_long_name__author_model_relation_with_long_name",
).get(id=chapter.id)
a = loaded.book_model_relation_with_long_name.author_model_relation_with_long_name
print({k: v for k, v in vars(a).items() if not k.startswith("_")})
assert (a.id, a.name, a.email, a.bio) == (author.id, "A-name", "a@example.test", "A-bio")
run_async(main())Run as The psycopg client uses The result depends on the column order, which comes from develop fails this query too (IndexError on both drivers), so this case is not a regression. A variant with the same cause does differ from develop. Here the join alias is short, but two columns of the related model share a long prefix: second scriptimport os
from tortoise import Tortoise, fields, run_async
from tortoise.models import Model
class Region(Model):
id = fields.IntField(primary_key=True)
name = fields.CharField(max_length=50)
class CustomerAccountBillingProfile(Model):
id = fields.IntField(primary_key=True)
shipping_address_line_number_one = fields.CharField(max_length=50)
shipping_address_line_number_two = fields.CharField(max_length=50)
region = fields.ForeignKeyField("models.Region")
class Invoice(Model):
id = fields.IntField(primary_key=True)
customer_account_billing_profile = fields.ForeignKeyField(
"models.CustomerAccountBillingProfile"
)
async def main():
await Tortoise.init(db_url=os.environ["DB_URL"], modules={"models": ["__main__"]})
await Tortoise.generate_schemas()
region = await Region.create(id=900, name="region")
profile = await CustomerAccountBillingProfile.create(
id=500,
shipping_address_line_number_one="one",
shipping_address_line_number_two="two",
region=region,
)
invoice = await Invoice.create(customer_account_billing_profile=profile)
loaded = await Invoice.all().select_related("customer_account_billing_profile").get(id=invoice.id)
p = loaded.customer_account_billing_profile
print({k: v for k, v in vars(p).items() if not k.startswith("_")})
assert (p.id, p.region_id) == (500, 900)
run_async(main())On develop this passes for seeds 0-7 on both drivers: the two long columns are not loaded, but The tests added in this PR pass for me on both drivers. None of their models has two columns whose aliases are equal after truncation ( |
Description
Postgres truncates identifiers to 63 bytes. Tortoise select_related JOINs build aliases such as table__long_relation__nested.field and execute_select used to recover field names by splitting those aliases on a dot. After truncation this raises IndexError (the separator is gone) or hydrates the wrong attribute.
Related columns were already sliced by position via select_related_idx. This change records the ordered field names for each related group when the query is built and zips them with row values, so field identity no longer depends on untruncated aliases. SQLite and MySQL keep the same SELECT shape; only hydration mapping changes.
Motivation and Context
Fixes #1902
How Has This Been Tested?
Checklist: