Skip to content

fix(queryset): hydrate select_related by field order - #2270

Open
vyrnsynx wants to merge 7 commits into
tortoise:developfrom
vyrnsynx:fix/postgres-long-join-alias-1902
Open

vyrnsynx wants to merge 7 commits into
tortoise:developfrom
vyrnsynx:fix/postgres-long-join-alias-1902

Conversation

@vyrnsynx

@vyrnsynx vyrnsynx commented Sep 2, 2026

Copy link
Copy Markdown

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?

  • New regression tests for nested long FK aliases, long OneToOne model plus column names, and only plus select_related
  • Existing select_related, only, and relations tests on SQLite
  • Helper test that positional row access survives duplicate truncated keys

Checklist:

  • My code follows the code style of this project.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

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>
@codspeed

codspeed Bot commented Sep 5, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 33.44%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 23 untouched benchmarks

Performance Changes

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)

Open in CodSpeed

@sinnercode228

Copy link
Copy Markdown

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 Author has more than one column:

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 DB_URL=psycopg://user:password@host/dbname python repro.py.

The psycopg client uses row_factory=dict_row, so the row is a dict. All four author aliases are cut to the same 63 bytes (chapter__book_model_relation_with_long_name__author_model_relat) and the dict keeps one entry for them: 8 columns are selected, the row has 5 entries. _row_keys_and_values takes the isinstance(row, dict) branch, the author's slice of the row holds a single value, and zip(field_names, related_values) pairs it with the first recorded field name.

The result depends on the column order, which comes from db_fields (a set) and so changes with PYTHONHASHSEED. Over seeds 0-7 I got ValueError: badly formed hexadecimal UUID string four times (a string ends up in id). The other four times the query returned a partial Author with a single field holding another column's value, e.g. only bio, set to the author's id, with seed 5; the assert then fails with an AttributeError.

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 script
import 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 id and region_id are right. On this branch it passes with asyncpg, with all four columns loaded. With psycopg it fails for 4 of the 8 seeds because id or region_id is missing, and with seed 1 p.id is 900, the region's id. In the other 4 seeds the assert passes but one long column holds the other one's value.

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 (LongJoinAuthor only has id), so they do not reach this path.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tortoise queries with long JOIN aliases raise exceptions when using Postgres as the backend database

2 participants