Skip to content

fix: update RelationIdLoader to use DriverUtils.getAlias - #11228

Merged
gioboa merged 9 commits into
typeorm:masterfrom
te1:fix/11227
Jan 18, 2026
Merged

gioboa merged 9 commits into
typeorm:masterfrom
te1:fix/11227

Conversation

@te1

@te1 te1 commented Jan 7, 2025 •

Copy link
Copy Markdown
Contributor

Update RelationIdLoader to use DriverUtils.getAlias to prevent aliases being possibly trimmed by database.

Closes: #11227

Description of change

Updates RelationIdLoader class to use DriverUtils.getAlias to generate column aliases. This resolves issues with databases that have hard limit on column aliases such as PostgreSQL and MySQL.

This is a follow up to #9380 which added getAlias but it missed a case for OneToOne relations with relationLoadStrategy: 'query'.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change (not needed)
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • Bug Fixes

    • Improved relation ID loading for one-to-one and many-to-one relations with very long entity/relation names by using dialect-aware aliasing. Prevents alias length issues on certain databases and ensures relations load correctly (including with relationLoadStrategy: "query").
  • Tests

    • Added end-to-end tests validating relation loading with long related-entity names to guard against alias length regressions across supported connections.

Update RelationIdLoader to use DriverUtils.getAlias to prevent aliases being possibly trimmed by database.

Closes: #11227
@gioboa
gioboa requested review from alumni and sgarner September 18, 2025 06:23
@coderabbitai

coderabbitai Bot commented Sep 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Updates RelationIdLoader to generate relation-ID mapping keys via DriverUtils.buildAlias. Adds a regression test suite (issue 11227) with two entities and a test verifying relation loading using a very long related-entity name under relationLoadStrategy: "query".

Changes

Cohort / File(s) Summary of Changes
Relation ID key generation
src/query-builder/RelationIdLoader.ts
Replaces raw string key construction with DriverUtils.buildAlias(...) in loadForManyToOneAndOneToOneOwner; no other logic changes.
Test entities for long relation name
test/github-issues/11227/entity/SomeEntity.ts, test/github-issues/11227/entity/SuperLongRelatedEntityNameDontAskWhy.ts
Adds two entities: a main entity with a long-named one-to-one relation and FK column; and the related entity with id and name columns.
Regression test for issue 11227
test/github-issues/11227/issue-11227.ts
Adds a test that sets up PG connections, saves related and main entities, loads relation via query strategy, and asserts the related name is "test".

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test (issue-11227)
    participant ORM as RelationIdLoader
    participant DU as DriverUtils
    participant DB as Database

    Test->>DB: Insert SuperLongRelatedEntityNameDontAskWhy
    Test->>DB: Insert SomeEntity with FK
    Test->>ORM: Load SomeEntity with relation (strategy: "query")
    ORM->>DU: buildAlias(driver, undefined, "<entity>_<relation>_<column>")
    note right of DU: Dialect-aware alias/key construction
    DU-->>ORM: alias/key
    ORM->>DB: Query to resolve relation IDs using built alias
    DB-->>ORM: Relation rows
    ORM-->>Test: SomeEntity with related entity loaded
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Suggested labels

comp: relations, need review help, size-m

Suggested reviewers

  • alumni
  • sgarner

Poem

I thump my paws on keys so bright,
Built aliases trimmed just right;
Long names hop, yet queries flow,
Relations found in tidy row.
With whiskered wit and tests in tow,
I squeak, “Ship it!”—off we go. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title is concise and accurately identifies the primary change — updating RelationIdLoader to use DriverUtils' alias helper — and matches the PR objectives and the code/test changes in the diff, so a reviewer scanning history will understand the main intent; the wording is specific (mentions the affected class and the utility) and avoids vague terms.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Sep 18, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11228
    

commit: a34a814

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/github-issues/11227/issue-11227.ts (2)

16-19: Option: broaden driver coverage (MySQL family also trims aliases).

If CI has these drivers configured, consider adding them to strengthen coverage.

-                enabledDrivers: ["postgres"],
+                enabledDrivers: ["postgres", "mysql", "mariadb"],

25-44: Optional: parallelize per-connection operations to speed up the test.

Safe to parallelize since each connection hits an isolated DB.

-        for (const connection of connections) {
-            const related = await connection
-                .getRepository(SuperLongRelatedEntityNameDontAskWhy)
-                .save({ name: "test" })
-            const entity = await connection.getRepository(SomeEntity).save({
-                superLongRelatedEntityNameDontAskWhy_id: related.id,
-            })
-            const result = await connection.getRepository(SomeEntity).findOne({
-                where: { id: entity.id },
-                relations: { superLongRelatedEntityNameDontAskWhy: true },
-                relationLoadStrategy: "query",
-            })
-            expect(result?.superLongRelatedEntityNameDontAskWhy?.name).to.eq("test")
-        }
+        await Promise.all(
+            connections.map(async (connection) => {
+                const related = await connection
+                    .getRepository(SuperLongRelatedEntityNameDontAskWhy)
+                    .save({ name: "test" })
+                const entity = await connection.getRepository(SomeEntity).save({
+                    superLongRelatedEntityNameDontAskWhy_id: related.id,
+                })
+                const result = await connection.getRepository(SomeEntity).findOne({
+                    where: { id: entity.id },
+                    relations: { superLongRelatedEntityNameDontAskWhy: true },
+                    relationLoadStrategy: "query",
+                })
+                expect(result?.superLongRelatedEntityNameDontAskWhy?.name).to.eq("test")
+            }),
+        )
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa3cd43 and abf63fb.

📒 Files selected for processing (4)
  • src/query-builder/RelationIdLoader.ts (1 hunks)
  • test/github-issues/11227/entity/SomeEntity.ts (1 hunks)
  • test/github-issues/11227/entity/SuperLongRelatedEntityNameDontAskWhy.ts (1 hunks)
  • test/github-issues/11227/issue-11227.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
test/github-issues/11227/issue-11227.ts (2)
src/connection/ConnectionManager.ts (1)
  • connections (16-18)
test/utils/test-utils.ts (3)
  • createTestingConnections (388-482)
  • reloadTestingDatabases (500-505)
  • closeTestingConnections (487-495)
test/github-issues/11227/entity/SomeEntity.ts (5)
test/github-issues/11227/entity/SuperLongRelatedEntityNameDontAskWhy.ts (1)
  • Entity (3-10)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
src/decorator/relations/OneToOne.ts (1)
  • OneToOne (30-74)
src/decorator/relations/JoinColumn.ts (1)
  • JoinColumn (31-48)
src/query-builder/RelationIdLoader.ts (1)
src/driver/DriverUtils.ts (1)
  • DriverUtils (8-297)
test/github-issues/11227/entity/SuperLongRelatedEntityNameDontAskWhy.ts (1)
test/github-issues/11227/entity/SomeEntity.ts (1)
  • Entity (10-21)
🔇 Additional comments (3)
test/github-issues/11227/issue-11227.ts (1)

12-45: Test adds the right regression coverage.

Repro uses a long related-entity name and relationLoadStrategy: "query" on Postgres—matches the failure mode and validates the fix.

test/github-issues/11227/entity/SuperLongRelatedEntityNameDontAskWhy.ts (1)

3-10: LGTM: minimal entity for repro.

Straightforward definition; nothing to change.

test/github-issues/11227/entity/SomeEntity.ts (1)

15-20: LGTM: explicit FK column + JoinColumn.

This models the long-FK scenario cleanly for the test.

Comment thread src/query-builder/RelationIdLoader.ts Resolved
@coveralls

coveralls commented Sep 18, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.952% (+0.01%) from 80.939%
when pulling a34a814 on te1:fix/11227
into 60b10c8 on typeorm:master.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to a34a814

CategorySuggestion                                                                                                                                    Impact
General
Optimize alias computation outside loop

Optimize performance by moving the DriverUtils.buildAlias call out of the every
loop to avoid redundant computations. Pre-calculate the column aliases before
filtering the relation IDs.

src/query-builder/RelationIdLoader.ts [147-160]

-return inverseColumns.every((column) => {
+const columnAliases = inverseColumns.map((column) =>
+    DriverUtils.buildAlias(
+        this.connection.driver,
+        undefined,
+        column.entityMetadata.name + "_" + column.propertyAliasName,
+    )
+);
+return inverseColumns.every((column, index) => {
     return column.compareEntityValue(
         entity,
-        relationId[
-            DriverUtils.buildAlias(
-                this.connection.driver,
-                undefined,
-                column.entityMetadata.name +
-                    "_" +
-                    column.propertyAliasName,
-            )
-        ],
+        relationId[columnAliases[index]],
     )
 })

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a performance issue where aliases are recomputed inside a loop and proposes a valid optimization by pre-calculating them, which improves efficiency.

Low
  • More

Previous suggestions

Suggestions up to commit 9938cc3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify correct DriverUtils method usage

Verify that DriverUtils.buildAlias is the correct method, as the PR title might
have mentioned DriverUtils.getAlias.

src/query-builder/RelationIdLoader.ts [464-476]

-const key = DriverUtils.buildAlias(
+const key = DriverUtils.getAlias(
     this.connection.driver,
     undefined,
     joinColumn.referencedColumn!.entityMetadata
         .name +
         "_" +
         relation.propertyPath.replace(".", "_") +
         "_" +
         joinColumn.referencedColumn!.propertyPath.replace(
             ".",
             "_",
         ),
 )
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies the code change but speculates about an inconsistency with the PR title, which is not provided. The implemented DriverUtils.buildAlias function is appropriate for truncating long aliases, which is the goal of the PR, and the new tests pass, confirming the fix. The suggestion to verify is valid but has a low impact as the current implementation appears correct.

Low
Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify correct DriverUtils method usage

Verify that DriverUtils.buildAlias is the correct method to use, as the PR title
may have mentioned DriverUtils.getAlias.

src/query-builder/RelationIdLoader.ts [464-476]

-const key = DriverUtils.buildAlias(
+const key = DriverUtils.getAlias(
     this.connection.driver,
     undefined,
     joinColumn.referencedColumn!.entityMetadata
         .name +
         "_" +
         relation.propertyPath.replace(".", "_") +
         "_" +
         joinColumn.referencedColumn!.propertyPath.replace(
             ".",
             "_",
         ),
 )
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies the new code but speculates about the correct function to use (buildAlias vs. getAlias) based on an external piece of information (the PR title). While asking for verification is reasonable, the implemented buildAlias function seems appropriate for creating an alias, and the new test passes with this implementation, suggesting it is likely correct.

Low

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 7, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify correct DriverUtils method usage

Verify that DriverUtils.buildAlias is the correct method to use, as the PR title
may have mentioned DriverUtils.getAlias.

src/query-builder/RelationIdLoader.ts [464-476]

-const key = DriverUtils.buildAlias(
+const key = DriverUtils.getAlias(
     this.connection.driver,
     undefined,
     joinColumn.referencedColumn!.entityMetadata
         .name +
         "_" +
         relation.propertyPath.replace(".", "_") +
         "_" +
         joinColumn.referencedColumn!.propertyPath.replace(
             ".",
             "_",
         ),
 )
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies the new code but speculates about the correct function to use (buildAlias vs. getAlias) based on an external piece of information (the PR title). While asking for verification is reasonable, the implemented buildAlias function seems appropriate for creating an alias, and the new test passes with this implementation, suggesting it is likely correct.

Low
  • More

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify correct DriverUtils method usage

Verify that DriverUtils.buildAlias is the correct method to use, as the PR title
may have mentioned DriverUtils.getAlias.

src/query-builder/RelationIdLoader.ts [464-476]

-const key = DriverUtils.buildAlias(
+const key = DriverUtils.getAlias(
     this.connection.driver,
     undefined,
     joinColumn.referencedColumn!.entityMetadata
         .name +
         "_" +
         relation.propertyPath.replace(".", "_") +
         "_" +
         joinColumn.referencedColumn!.propertyPath.replace(
             ".",
             "_",
         ),
 )
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies the new code but speculates about the correct function to use (buildAlias vs. getAlias) based on an external piece of information (the PR title). While asking for verification is reasonable, the implemented buildAlias function seems appropriate for creating an alias, and the new test passes with this implementation, suggesting it is likely correct.

Low
  • More

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

Grey Divider


Looking for bugs?

Come back again in a few minutes. An AI review agent is analysing this pull request

Grey Divider

Qodo Logo

@gioboa gioboa changed the title fix: Update RelationIdLoader to use DriverUtils.getAlias fix: update RelationIdLoader to use DriverUtils.getAlias Jan 18, 2026

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great to me 👏
Thanks @te1

@naorpeled

Copy link
Copy Markdown
Member

/agentic_review

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 18, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Remediation recommended

1. Test added to github-issues directory 📘 Rule violation ✓ Correctness
Description
• The PR adds a test under test/github-issues/11227/ for issue #11227, which fixes a bug in
  RelationIdLoader.
• According to the compliance rule, issue fixes should preferably add or update tests in
  test/functional with an issue reference in comments.
• The test is similar to existing issue #9379 test, which is also in github-issues, suggesting this
  may be acceptable for regression tests, but the rule prefers functional tests.
Code

test/github-issues/11227/issue-11227.test.ts[R1-45]

+import "reflect-metadata"
+import { expect } from "chai"
+import { DataSource } from "../../../src/data-source/DataSource"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { SomeEntity } from "./entity/SomeEntity"
+import { SuperLongRelatedEntityNameDontAskWhy } from "./entity/SuperLongRelatedEntityNameDontAskWhy"
+
+describe("github issues > #11227 RelationIdLoader is not consistently respecting maxAliasLength", () => {
+    let connections: DataSource[]
+    before(
+        async () =>
+            (connections = await createTestingConnections({
+                entities: [__dirname + "/entity/*{.js,.ts}"],
+                enabledDrivers: ["postgres"],
+            })),
+    )
+    beforeEach(() => reloadTestingDatabases(connections))
+    after(() => closeTestingConnections(connections))
+
+    it("should fetch related entities properly", async () => {
+        for (const connection of connections) {
+            const related = await connection
+                .getRepository(SuperLongRelatedEntityNameDontAskWhy)
+                .save({ name: "test" })
+
+            const entity = await connection.getRepository(SomeEntity).save({
+                superLongRelatedEntityNameDontAskWhy_id: related.id,
+            })
+
+            const result = await connection.getRepository(SomeEntity).findOne({
+                where: { id: entity.id },
+                relations: { superLongRelatedEntityNameDontAskWhy: true },
+                relationLoadStrategy: "query",
+            })
+
+            expect(result?.superLongRelatedEntityNameDontAskWhy?.name).to.eq(
+                "test",
+            )
+        }
+    })
+})
Evidence
The compliance checklist (PR Compliance ID 3) states that issue fixes should add or update tests in
test/functional with an issue reference when applicable, and that adding tests only under
test/github-issues without a clear reason is a failure. The PR adds a test exclusively under
test/github-issues/11227/ without adding or updating functional tests. While there is precedent for
similar tests (issue #9379) being in github-issues, the DEVELOPER.md documentation states 'To create
a new test, check the relevant functional tests' and 'If the test is for a specific regression or
issue opened on GitHub, add a comment to the tests mentioning the issue number', suggesting
functional tests with issue references are preferred.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11227/issue-11227.test.ts[1-45]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test for issue #11227 is added only under test/github-issues/ without a corresponding functional test or clear justification.

## Issue Context
The compliance rule &#x27;Prefer functional tests over per-issue tests&#x27; states that issue fixes should add or update tests in test/functional with an issue reference in comments when applicable. The DEVELOPER.md documentation also recommends checking relevant functional tests and adding issue references in comments.

## Fix Focus Areas
- test/github-issues/11227/issue-11227.test.ts[1-45]
- Consider adding to test/functional/query-builder/relation-id/ with issue reference

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Previous review results

Review updated until commit a34a814

Results up to commit 728b42f


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review
Results up to commit 6df10d1


🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider
Action required
✅ 1. Inconsistent alias handling for primary columns 🐞 Bug ✓ Correctness
Suggestion Impact:The suggestion directly impacted the commit. The commit implements the exact fix suggested: wrapping primary column key construction with DriverUtils.buildAlias at lines 24-32 (corresponding to the suggested fix at lines 440-443). Additionally, the commit extends this fix to other locations in the file (lines 9-15 and lines 47-82) that had similar inconsistencies, applying the same pattern throughout the codebase.

code diff:

+                        const key = DriverUtils.buildAlias(
+                            this.connection.driver,
+                            undefined,
                             primaryColumn.entityMetadata.name +
-                            "_" +
-                            primaryColumn.propertyPath.replace(".", "_")
+                                "_" +
+                                primaryColumn.propertyPath.replace(".", "_"),
+                        )

Description
• The PR fixes join column keys to use DriverUtils.buildAlias (lines 464-476), but primary column
  keys at lines 440-443 still use direct string concatenation without DriverUtils.buildAlias
• This creates a mismatch: when the code returns early with in-memory relationIdMaps (line 492),
  primary column keys can exceed maxAliasLength, but if it falls through to SQL queries (lines
  498-504), those same keys are properly truncated
• When entity names are long enough to trigger alias truncation, the in-memory path and SQL path
  will produce different key formats, causing inconsistent behavior depending on whether
  relatedEntities are provided
Code

src/query-builder/RelationIdLoader.ts[R464-476]

+                            const key = DriverUtils.buildAlias(
+                                this.connection.driver,
+                                undefined,
                                joinColumn.referencedColumn!.entityMetadata
                                    .name +
-                                "_" +
-                                relation.propertyPath.replace(".", "_") +
-                                "_" +
-                                joinColumn.referencedColumn!.propertyPath.replace(
-                                    ".",
-                                    "_",
-                                )
+                                    "_" +
+                                    relation.propertyPath.replace(".", "_") +
+                                    "_" +
+                                    joinColumn.referencedColumn!.propertyPath.replace(
+                                        ".",
+                                        "_",
+                                    ),
+                            )
Evidence
The code shows that primary column keys are constructed differently in the in-memory path (lines
440-443) versus the SQL query path (lines 498-504). The in-memory path uses direct concatenation
while the SQL path uses DriverUtils.buildAlias. This inconsistency means the same function can
return different key formats depending on the code path taken.

src/query-builder/RelationIdLoader.ts[440-443]
src/query-builder/RelationIdLoader.ts[498-504]
src/query-builder/RelationIdLoader.ts[491-492]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue Description
The primary column keys in the in-memory relationIdMap construction are not using DriverUtils.buildAlias, creating inconsistency with the SQL query path and the newly fixed join column keys. This can cause different key formats depending on the code path taken.

## Issue Context
The PR already fixes join column keys to use DriverUtils.buildAlias (lines 464-476), but missed the primary column keys at lines 440-443. When entity names exceed maxAliasLength, the in-memory path will have different keys than the SQL path.

## Fix Focus Areas
- src/query-builder/RelationIdLoader.ts[440-443]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


✅ 2. Inconsistent key construction in OneToMany loader 🐞 Bug ✓ Correctness
Suggestion Impact:The commit directly implements the suggestion by wrapping the joinColumnName and primaryColumnName key constructions with DriverUtils.buildAlias in the loadForOneToManyAndOneToOneNotOwner function (lines 47-82 and 133-168 of the diff), fixing the inconsistency between in-memory and SQL query paths.

code diff:

+                            const joinColumnName = DriverUtils.buildAlias(
+                                this.connection.driver,
+                                undefined,
                                 joinColumn.referencedColumn!.entityMetadata
                                     .name +
-                                "_" +
-                                joinColumn.referencedColumn!.propertyPath.replace(
-                                    ".",
-                                    "_",
-                                )
-                            const primaryColumnName =
+                                    "_" +
+                                    joinColumn.referencedColumn!.propertyPath.replace(
+                                        ".",
+                                        "_",
+                                    ),
+                            )
+                            const primaryColumnName = DriverUtils.buildAlias(
+                                this.connection.driver,
+                                undefined,
                                 joinColumn.entityMetadata.name +
-                                "_" +
-                                originalRelation.propertyPath.replace(
-                                    ".",
-                                    "_",
-                                ) +
-                                "_" +
-                                joinColumn.propertyPath.replace(".", "_")
+                                    "_" +
+                                    originalRelation.propertyPath.replace(
+                                        ".",
+                                        "_",
+                                    ) +
+                                    "_" +
+                                    joinColumn.propertyPath.replace(".", "_"),
+                            )

Description
• The loadForOneToManyAndOneToOneNotOwner function constructs keys without DriverUtils.buildAlias at
  lines 607-625 for the in-memory return path
• However, the SQL query path in the same function uses DriverUtils.buildAlias for the same keys at
  lines 638-660
• This creates the same inconsistency issue: when entity names exceed maxAliasLength, the in-memory
  path returns different key formats than the SQL path, causing unpredictable behavior
Code

src/query-builder/RelationIdLoader.ts[R464-476]

+                            const key = DriverUtils.buildAlias(
+                                this.connection.driver,
+                                undefined,
                                joinColumn.referencedColumn!.entityMetadata
                                    .name +
-                                "_" +
-                                relation.propertyPath.replace(".", "_") +
-                                "_" +
-                                joinColumn.referencedColumn!.propertyPath.replace(
-                                    ".",
-                                    "_",
-                                )
+                                    "_" +
+                                    relation.propertyPath.replace(".", "_") +
+                                    "_" +
+                                    joinColumn.referencedColumn!.propertyPath.replace(
+                                        ".",
+                                        "_",
+                                    ),
+                            )
Evidence
The loadForOneToManyAndOneToOneNotOwner function shows the same pattern as the fixed function:
in-memory keys use direct concatenation (lines 607-625) while SQL query keys use
DriverUtils.buildAlias (lines 638-660). This is the same bug that the PR is fixing, but in a
different function.

src/query-builder/RelationIdLoader.ts[607-614]
src/query-builder/RelationIdLoader.ts[615-623]
src/query-builder/RelationIdLoader.ts[653-659]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue Description
The loadForOneToManyAndOneToOneNotOwner function has the same issue that this PR is fixing in loadForManyToOneAndOneToOneOwner. The in-memory key construction doesn&#x27;t use DriverUtils.buildAlias while the SQL path does.

## Issue Context
This is the same bug pattern as the one being fixed in the PR, but in a different function. When entity names exceed maxAliasLength, the in-memory return path will have different keys than the SQL query path.

## Fix Focus Areas
- src/query-builder/RelationIdLoader.ts[607-614]
- src/query-builder/RelationIdLoader.ts[615-623]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
3. Test in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix adds tests under test/github-issues/11227 instead of adding or updating tests in
  test/functional.
• Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue
  reference in the test comment when applicable.
• The test should be in the functional test suite to ensure long-term maintenance and prevent
  regressions.
Code

test/github-issues/11227/issue-11227.test.ts[R1-45]

+import "reflect-metadata"
+import { expect } from "chai"
+import { DataSource } from "../../../src/data-source/DataSource"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { SomeEntity } from "./entity/SomeEntity"
+import { SuperLongRelatedEntityNameDontAskWhy } from "./entity/SuperLongRelatedEntityNameDontAskWhy"
+
+describe("github issues > #11227 RelationIdLoader is not consistently respecting maxAliasLength", () => {
+    let connections: DataSource[]
+    before(
+        async () =>
+            (connections = await createTestingConnections({
+                entities: [__dirname + "/entity/*{.js,.ts}"],
+                enabledDrivers: ["postgres"],
+            })),
+    )
+    beforeEach(() => reloadTestingDatabases(connections))
+    after(() => closeTestingConnections(connections))
+
+    it("should fetch related entities properly", async () => {
+        for (const connection of connections) {
+            const related = await connection
+                .getRepository(SuperLongRelatedEntityNameDontAskWhy)
+                .save({ name: "test" })
+
+            const entity = await connection.getRepository(SomeEntity).save({
+                superLongRelatedEntityNameDontAskWhy_id: related.id,
+            })
+
+            const result = await connection.getRepository(SomeEntity).findOne({
+                where: { id: entity.id },
+                relations: { superLongRelatedEntityNameDontAskWhy: true },
+                relationLoadStrategy: "query",
+            })
+
+            expect(result?.superLongRelatedEntityNameDontAskWhy?.name).to.eq(
+                "test",
+            )
+        }
+    })
+})
Evidence
The PR adds a new test file under test/github-issues/11227/issue-11227.test.ts to validate the
fix. According to compliance rule 3, issue fixes should preferably add or update tests in
test/functional rather than only adding tests under test/github-issues. While the test is valid
and tests the fix, it would be better placed in the functional test suite (e.g.,
test/functional/relations or test/functional/query-builder) with a comment referencing issue
#11227.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11227/issue-11227.test.ts[1-45]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test for issue #11227 is currently in `test/github-issues/11227` but should be in the functional test suite per project conventions.

## Issue Context
Compliance rule 3 states: &quot;Issue fixes should add or update tests in test/functional, with an issue reference in the test comment when applicable.&quot; The test validates that `RelationIdLoader` correctly uses `DriverUtils.buildAlias` to handle long entity names with `relationLoadStrategy: &#x27;query&#x27;`.

## Fix Focus Areas
- test/github-issues/11227/issue-11227.test.ts[1-45]
- Consider moving to test/functional/relations or test/functional/query-builder
- Add a comment in the test referencing issue #11227

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 6df10d1

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 728b42f

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit a34a814

@gioboa
gioboa merged commit cd7ab97 into typeorm:master Jan 18, 2026
38 checks passed
@te1
te1 deleted the fix/11227 branch January 19, 2026 00:04
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

RelationIdLoader is not consistently respecting maxAliasLength

5 participants