Skip to content

fix: eager load relation strategy - #11326

Merged
alumni merged 58 commits into
typeorm:masterfrom
SharkSharp:fix/9006-eager-load-relation-strategy
Mar 23, 2026
Merged

alumni merged 58 commits into
typeorm:masterfrom
SharkSharp:fix/9006-eager-load-relation-strategy

Conversation

@SharkSharp

@SharkSharp SharkSharp commented Mar 6, 2025 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #9006

This PR addresses the issue where the relationLoadStrategy: 'query' option did not split the entire query into multiple queries as expected. The functionality of loading eager relations with new queries instead of joins was not implemented.

Changes Made

  1. Implemented the functionality to load eager relations using separate queries instead of joins.
  2. Fixed an issue where some queries were fetching data that the ORM already had, to link the entities.
  3. Addressed the eager loop problem by allowing loops in eager loading and stopping when it reaches any already performed query. Options to either throw an error to alert the user or let TypeORM handle it may be added.
  4. Identified a lack of configuration showing RelationLoader methods that should or should not load the eager relations according to the query option loadEagerRelations. This has been added.

Ideas for Future Improvements

  • Add an option in all relations called loadStrategy or use the existing eager as a string to specify whether eager loading should be performed as a join or query. This would provide detailed control over all eager loads, significantly improving performance.

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 Eager relations do not respect relationLoadStrategy #9006
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change - N/A
  • The new commits follow conventions explained in CONTRIBUTING.md

@coveralls

coveralls commented Mar 6, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.342% (+0.07%) from 73.277%
when pulling a6746fc on SharkSharp:fix/9006-eager-load-relation-strategy
into 7038fa1 on typeorm:master.

@alumni alumni changed the title Fix/9006 eager load relation strategy fix: eager load relation strategy Mar 10, 2025
@SharkSharp

SharkSharp commented Apr 30, 2025 •

Copy link
Copy Markdown
Contributor Author

Fixed nested eager relations ignoring loadEagerRelations option

I fixed a bug where nested eager relations were being loaded regardless of the loadEagerRelations query option setting. Previously, while the system respected this option for first-level relations, it would ignore it when loading eager relations of relations.

The fix ensures that the loadEagerRelations option is properly respected throughout the entire relation chain. I've also added a test case that asserts it.

I'll check if this error is occurring during relationLoadStrategy === "join" and fix it if happens

@pkg-pr-new

pkg-pr-new Bot commented Jan 5, 2026 •

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

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

commit: a6746fc

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

Can I ask you to fix the issues with formatting please?

@SharkSharp

Copy link
Copy Markdown
Contributor Author

Can I ask you to fix the issues with formatting please?

Fixed the issues. Let me know if there is anything else I could do.

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

This file should be test/github-issues/9006/issue-9006.test.ts with .test.ts otherwise it will not run.

@SharkSharp

Copy link
Copy Markdown
Contributor Author

This file should be test/github-issues/9006/issue-9006.test.ts with .test.ts otherwise it will not run.

Fixed. Sry about that.
I am available should any remaining issues arise.

@gioboa
gioboa requested a review from alumni January 7, 2026 19:09
@pkuczynski
pkuczynski force-pushed the fix/9006-eager-load-relation-strategy branch from 199162b to f2150bd Compare March 22, 2026 22:34
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit f2150bd

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

Copy link
Copy Markdown

Persistent review updated to latest commit d81738d

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

Copy link
Copy Markdown

Persistent review updated to latest commit 246c351

@pkuczynski
pkuczynski force-pushed the fix/9006-eager-load-relation-strategy branch from 246c351 to 0505163 Compare March 23, 2026 00:38
@pkuczynski pkuczynski closed this Mar 23, 2026
@pkuczynski pkuczynski reopened this Mar 23, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Implement eager relation loading via query strategy with circular dependency handling

🐞 Bug fix ✨ Enhancement

Grey Divider

Walkthroughs

Description
• Implement relationLoadStrategy: 'query' to load eager relations via separate queries instead of
  joins
• Add cycle detection for circular eager relation chains to prevent infinite recursion
• Fix type coercion issues in relation ID loading for database drivers like CockroachDB
• Respect loadEagerRelations option in relation loading strategies
• Add comprehensive test coverage for query-based relation loading strategies
Diagram
flowchart LR
  A["relationLoadStrategy: query"] --> B["SelectQueryBuilder"]
  B --> C["RelationLoader.applyEagerRelations"]
  C --> D["concatRelationMetadata for query strategy"]
  D --> E["QueryStrategyRelationIdLoader"]
  E --> F["RelationIdLoader with type coercion"]
  F --> G["prepareHydratedValue for driver compatibility"]
  B --> H["eagerLoadChain cycle detection"]
  H --> I["Prevent infinite recursion in circular relations"]
Loading

Grey Divider

File Changes

1. src/query-builder/RelationIdLoader.ts Bug fix, enhancement +76/-10

Add type coercion and cycle detection to relation ID loading

src/query-builder/RelationIdLoader.ts


2. src/query-builder/RelationLoader.ts ✨ Enhancement +44/-20

Implement query strategy for eager relation loading

src/query-builder/RelationLoader.ts


3. src/query-builder/SelectQueryBuilder.ts ✨ Enhancement +79/-34

Add eager load chain tracking and query strategy support

src/query-builder/SelectQueryBuilder.ts


View more (12)
4. test/functional/relations/load-strategy/query/entity/Author.ts 🧪 Tests +28/-0

New test entity with eager ManyToMany relations

test/functional/relations/load-strategy/query/entity/Author.ts


5. test/functional/relations/load-strategy/query/entity/Book.ts 🧪 Tests +27/-0

New test entity with eager OneToMany relations

test/functional/relations/load-strategy/query/entity/Book.ts


6. test/functional/relations/load-strategy/query/entity/Category.ts 🧪 Tests +5/-1

Update import paths for test entity

test/functional/relations/load-strategy/query/entity/Category.ts


7. test/functional/relations/load-strategy/query/entity/Comment.ts 🧪 Tests +32/-0

New test entity for relation loading tests

test/functional/relations/load-strategy/query/entity/Comment.ts


8. test/functional/relations/load-strategy/query/entity/Profile.ts 🧪 Tests +21/-0

New test entity with eager OneToOne relation

test/functional/relations/load-strategy/query/entity/Profile.ts


9. test/functional/relations/load-strategy/query/entity/Review.ts 🧪 Tests +21/-0

New test entity with eager ManyToOne relation

test/functional/relations/load-strategy/query/entity/Review.ts


10. test/functional/relations/load-strategy/query/relation-load-strategy-query.test.ts 🧪 Tests +434/-0

Comprehensive test suite for query-based relation loading

test/functional/relations/load-strategy/query/relation-load-strategy-query.test.ts


11. test/functional/relations/load-strategy/circular/entity/Journalist.ts 🧪 Tests +19/-0

New test entity for circular eager relation testing

test/functional/relations/load-strategy/circular/entity/Journalist.ts


12. test/functional/relations/load-strategy/circular/entity/Magazine.ts 🧪 Tests +19/-0

New test entity for circular eager relation testing

test/functional/relations/load-strategy/circular/entity/Magazine.ts


13. test/functional/relations/load-strategy/circular/entity/Publisher.ts 🧪 Tests +19/-0

New test entity for circular eager relation testing

test/functional/relations/load-strategy/circular/entity/Publisher.ts


14. test/functional/relations/load-strategy/circular/relation-load-strategy-circular.test.ts 🧪 Tests +67/-0

Test suite for circular eager relation cycle detection

test/functional/relations/load-strategy/circular/relation-load-strategy-circular.test.ts


15. test/functional/relations/self-referencing-query/self-referencing-query.test.ts 🧪 Tests +0/-74

Remove obsolete self-referencing query tests

test/functional/relations/self-referencing-query/self-referencing-query.test.ts


Grey Divider

Qodo Logo

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 0505163

@pkuczynski

Copy link
Copy Markdown
Member

A few more fixes pushed after running CI and SonarQube analysis:

Bug fixes:

  1. loadEagerRelations: false not propagated to RelationLoader — When using query strategy with loadEagerRelations: false and explicit relations, nested eager relations were still loaded because RelationLoader had no access to the parent's findOptions. Threaded loadEagerRelations through RelationIdLoader → RelationLoader and extracted a shared applyEagerRelations helper to eliminate code duplication. (bc8d306, f2150bd)

  2. Hydration missing in two RelationIdLoader paths — prepareHydratedValue was only applied in loadForManyToMany but not in loadForManyToOneAndOneToOneOwner or loadForOneToManyAndOneToOneNotOwner. This caused nested eager relation loading to fail on CockroachDB (and potentially other drivers) where raw query results need type conversion (e.g. bigint → number). Extracted the shared pattern into executeAndHydrateRaw. (8d5a322, a6746fc)

  3. Circular eager chains (A→B→C→A) caused infinite recursion — The metadata validator only catches direct A↔B cycles. Longer chains like Publisher→Magazine→Journalist→Publisher bypassed it and recursed indefinitely with the query strategy. Added a per-branch visited set (eagerLoadChain) that propagates to child query builders — each parallel branch gets its own copy so they don't interfere. (0505163)

Code quality (SonarQube):

  1. Replaced ! non-null assertions with proper null guards on referencedColumn and mainAlias. (0f1d5ca)

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Eager loading docs now inaccurate 📘 Rule violation ⚙ Maintainability
Description
Eager relations behavior now differs when relationLoadStrategy is query (it no longer uses
JOIN-based eager loading), but the docs still state eager relations are loaded via LEFT JOIN
without describing the strategy-dependent behavior. This is a user-facing behavior change without
corresponding documentation updates.
Code

src/query-builder/SelectQueryBuilder.ts[R3362-3378]

+            if (
+                this.findOptions.loadEagerRelations !== false &&
+                this.expressionMap.mainAlias
+            ) {
+                if (this.expressionMap.relationLoadStrategy === "join") {
+                    FindOptionsUtils.joinEagerRelations(
+                        this,
+                        this.expressionMap.mainAlias.name,
+                        this.expressionMap.mainAlias.metadata,
+                    )
+                } else if (
+                    this.expressionMap.relationLoadStrategy === "query"
+                ) {
+                    this.concatRelationMetadata(
+                        ...this.expressionMap.mainAlias.metadata.eagerRelations,
+                    )
+                }
Evidence
The PR changes eager relation loading to use concatRelationMetadata(...) when
relationLoadStrategy === "query", altering observable ORM behavior. The docs currently describe
eager relations as being loaded via LEFT JOIN, which is no longer accurate for the query strategy,
and no documentation updates are included in the PR.

Rule 2: Docs updated for user-facing changes
src/query-builder/SelectQueryBuilder.ts[3362-3378]
docs/docs/relations/5-eager-and-lazy-relations.md[64-70]

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

## Issue description
Eager relation loading behavior is now strategy-dependent (`relationLoadStrategy: "query"` loads eager relations via follow-up queries instead of JOINs), but the docs still describe eager relations as being loaded via `LEFT JOIN` without mentioning this.

## Issue Context
The PR changes eager-loading internals so that when `relationLoadStrategy === "query"`, eager relations are added via `concatRelationMetadata(...)` rather than `FindOptionsUtils.joinEagerRelations(...)`, which changes user-observable SQL behavior.

## Fix Focus Areas
- docs/docs/relations/5-eager-and-lazy-relations.md[64-70]
- src/query-builder/SelectQueryBuilder.ts[3362-3378]

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


2. Eager cycle key collision 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder prevents circular eager recursion by tracking visited entities using
EntityMetadata.name, which is not guaranteed unique (it’s derived from the entity class name when
available). In projects with duplicate entity class names, this can cause false cycle detection and
silently skip eager loads under relationLoadStrategy: "query".
Code

src/query-builder/SelectQueryBuilder.ts[R3634-3659]

+                    // Prevent infinite recursion from circular eager
+                    // chains (e.g. A→B→C→A). Each branch maintains its
+                    // own visited set so parallel branches don't interfere.
+                    if (relation.isEager) {
+                        const targetEntity = relation.inverseEntityMetadata.name
+                        if (this.eagerLoadChain.has(targetEntity)) return
+                    }
+
                    const relationTarget = relation.inverseEntityMetadata.target
                    const relationAlias =
                        relation.inverseEntityMetadata.targetName

                    const queryBuilder = this.createQueryBuilder(queryRunner)
                        .select(relationAlias)
                        .from(relationTarget, relationAlias)
-                        .setFindOptions({
-                            select: this.findOptions.select
-                                ? OrmUtils.deepValue(
-                                      this.findOptions.select,
-                                      relation.propertyPath,
-                                  )
-                                : undefined,
-                            order: this.findOptions.order
-                                ? OrmUtils.deepValue(
-                                      this.findOptions.order,
-                                      relation.propertyPath,
-                                  )
-                                : undefined,
-                            relations: this.findOptions.relations
-                                ? OrmUtils.deepValue(
-                                      this.findOptions.relations,
-                                      relation.propertyPath,
-                                  )
-                                : undefined,
-                            withDeleted: this.findOptions.withDeleted,
-                            relationLoadStrategy:
-                                this.findOptions.relationLoadStrategy,
-                        })
+
+                    // Propagate eager load chain with current entity
+                    // added, so the child detects cycles in its branch
+                    if (relation.isEager) {
+                        queryBuilder.eagerLoadChain = new Set(
+                            this.eagerLoadChain,
+                        )
+                        queryBuilder.eagerLoadChain.add(
+                            relation.entityMetadata.name,
+                        )
+                    }
Evidence
The cycle guard uses relation.inverseEntityMetadata.name as the visited key and propagates it
across nested query builders; however EntityMetadata.name is derived from targetName (JS
constructor name) when available, which can collide across entities. This makes the visited-set
ambiguous and can skip eager loads incorrectly in a single eager chain when two different entities
share the same class name.

src/query-builder/SelectQueryBuilder.ts[3624-3705]
src/metadata/EntityMetadata.ts[999-1044]

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

### Issue description
`eagerLoadChain` uses `EntityMetadata.name` as the cycle-detection key in query-strategy eager loading. `name` can collide (e.g., two entity classes named `User` in different modules/schemas), causing false positives and skipped eager loads.

### Issue Context
The cycle-prevention logic is used only when `relation.isEager` and `relationLoadStrategy === "query"`.

### Fix Focus Areas
- Use a stable unique identifier for entities in the chain (e.g., `EntityMetadata.tablePath` or a composite like `${metadata.tablePath}:${metadata.targetName}`) instead of `metadata.name`.
- Keep the existing per-branch Set copying behavior.

- src/query-builder/SelectQueryBuilder.ts[3634-3659]
- src/metadata/EntityMetadata.ts[999-1044]

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


3. Relation metadata de-dupe wrong 🐞 Bug ✓ Correctness
Description
concatRelationMetadata de-duplicates only by RelationMetadata.propertyPath, which can collide
across different entity metadatas; this can drop required relation loads or mix relation targets
under relationLoadStrategy: "query". This is particularly risky for code paths that recursively
add relations from multiple metadata contexts (e.g., TreeRepository’s
FindOptionsUtils.applyRelationsRecursively).
Code

src/query-builder/SelectQueryBuilder.ts[R3403-3411]

+    public concatRelationMetadata(...relationMetadata: RelationMetadata[]) {
+        const newRelationMetadata = relationMetadata.filter(
+            (metadata) =>
+                !this.relationMetadatas.some(
+                    (existentMetadata) =>
+                        existentMetadata.propertyPath === metadata.propertyPath,
+                ),
+        )
+        this.relationMetadatas.push(...newRelationMetadata)
Evidence
FindOptionsUtils.applyRelationsRecursively adds relation metadata during recursion, and in
query-strategy mode it recurses using relation.inverseEntityMetadata (i.e., different entity
contexts). With de-dupe keyed only by propertyPath, relations from different entity types but the
same property name (e.g., repeated/self-referencing parent, or common author, user, etc.) can
be suppressed. Additionally, executeEntitiesAndRawResults later iterates a single
relationMetadatas list to load relations for the root entities, so mixing relation metadatas
from non-root contexts can lead to wrong/empty relation loading queries.

src/query-builder/SelectQueryBuilder.ts[3403-3412]
src/find-options/FindOptionsUtils.ts[228-310]
src/repository/TreeRepository.ts[43-75]
src/query-builder/SelectQueryBuilder.ts[3624-3708]

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

### Issue description
`SelectQueryBuilder.concatRelationMetadata` de-duplicates by `propertyPath` only. Under query-strategy, some code paths can accumulate relations from multiple entity contexts (notably recursive relation application), making `propertyPath` insufficient and causing missing relation loads or incorrect relation loading.

### Issue Context
- `FindOptionsUtils.applyRelationsRecursively` recurses into `relation.inverseEntityMetadata` for query-strategy.
- `executeEntitiesAndRawResults` later loads every `relationMetadatas` entry against the root `entities` array.

### Fix Focus Areas
- Change de-duplication key to include the relation’s owning entity context, e.g. `${relation.entityMetadata.tablePath}:${relation.propertyPath}` (or `entityMetadata.name` + `tablePath`), not just `propertyPath`.
- Consider guarding against adding relation metadata that doesn’t apply to the current root entity set when using query strategy.

- src/query-builder/SelectQueryBuilder.ts[3403-3412]
- src/find-options/FindOptionsUtils.ts[228-310]
- src/query-builder/SelectQueryBuilder.ts[3624-3708]
- src/repository/TreeRepository.ts[43-75]

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


Grey Divider

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

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (1) 📎 Requirement gaps (0) 📐 Spec deviations (0)

Grey Divider


Action required

1. Missing docs for query strategy 📘 Rule violation ⚙ Maintainability
Description
This PR changes user-facing behavior so eager relations honor relationLoadStrategy: "query", but
no documentation updates are included. Users relying on docs may not discover or correctly use the
new eager-loading behavior.
Code

src/query-builder/SelectQueryBuilder.ts[R3362-3378]

+            if (
+                this.findOptions.loadEagerRelations !== false &&
+                this.expressionMap.mainAlias
+            ) {
+                if (this.expressionMap.relationLoadStrategy === "join") {
+                    FindOptionsUtils.joinEagerRelations(
+                        this,
+                        this.expressionMap.mainAlias.name,
+                        this.expressionMap.mainAlias.metadata,
+                    )
+                } else if (
+                    this.expressionMap.relationLoadStrategy === "query"
+                ) {
+                    this.concatRelationMetadata(
+                        ...this.expressionMap.mainAlias.metadata.eagerRelations,
+                    )
+                }
Evidence
Compliance ID 2 requires docs updates for user-facing API/usage changes. The diff changes eager
relation loading behavior based on relationLoadStrategy (join vs query) but only code/tests were
updated and no documentation changes are shown in the PR diff.

Rule 2: Docs updated for user-facing changes
src/query-builder/SelectQueryBuilder.ts[3362-3378]

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

## Issue description
User-facing eager-relation behavior changes when `relationLoadStrategy` is `"query"`, but the PR does not include documentation updates describing the new behavior and usage.

## Issue Context
The code now conditionally loads eager relations via `join` vs `query` strategy (and introduces circular eager safeguards), which affects how `.find*()` behaves for users configuring `relationLoadStrategy` and `loadEagerRelations`.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3362-3378]

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


2. Circular eager test bypasses validator 🐞 Bug ✓ Correctness
Description
The new circular-eager test entities (Publisher→Magazine→Journalist→Publisher) each have `eager:
true on a ManyToOne relation, but EntityMetadataValidator.validateEagerRelations` throws a
TypeORMError when any relation's inverse side is also eager. These test entities will fail
DataSource initialization before any test runs.
Code

test/functional/relations/load-strategy/circular/entity/Journalist.ts[R17-18]

+    @ManyToOne(() => Publisher, { eager: true, nullable: true })
+    publisher?: Publisher
Evidence
EntityMetadataValidator.validateEagerRelations (src/metadata-builder/EntityMetadataValidator.ts
lines 343-357) iterates every entity's eagerRelations and throws if relation.inverseRelation.isEager
is true. In the circular test, Publisher.magazine is eager and Magazine.journalist is eager and
Journalist.publisher is eager. Each pair (Publisher→Magazine and Magazine→Journalist and
Journalist→Publisher) forms a bidirectional eager cycle that will trigger the validator. The test
entities are ManyToOne without an explicit inverse side, but TypeORM still resolves the
inverseRelation from the other side's @ManyToMany/@OneToMany/@ManyToOne declarations. If the inverse
is also eager the validator throws before any query runs.

test/functional/relations/load-strategy/circular/entity/Journalist.ts[17-18]
src/metadata-builder/EntityMetadataValidator.ts[343-357]

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 circular eager test entities (Publisher, Magazine, Journalist) each declare `eager: true` on a `@ManyToOne` relation forming a cycle. `EntityMetadataValidator.validateEagerRelations` throws when `relation.inverseRelation && relation.inverseRelation.isEager`. Confirm whether the validator only fires when both sides of the *same* relation are eager (i.e., both the owning and inverse side of the same relation pair), or whether it fires for any chain. If the validator only checks direct inverse pairs and ManyToOne without explicit inverse does not trigger it, the test is fine. If it does trigger, the test entities need to be redesigned so that only one side of each pair is eager, or the validator needs to be updated to allow query-strategy circular chains.

## Issue Context
- Validator: `src/metadata-builder/EntityMetadataValidator.ts[343-357]`
- Test entities: `test/functional/relations/load-strategy/circular/entity/`
- The validator checks `relation.inverseRelation && relation.inverseRelation.isEager`

## Fix Focus Areas
- test/functional/relations/load-strategy/circular/entity/Journalist.ts[17-18]
- test/functional/relations/load-strategy/circular/entity/Magazine.ts[17-18]
- test/functional/relations/load-strategy/circular/entity/Publisher.ts[17-18]
- src/metadata-builder/EntityMetadataValidator.ts[343-357]

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



Remediation recommended

3. Skipped columns break relation ID matching 🐞 Bug ✓ Correctness
Description
In RelationIdLoader.loadForManyToMany, loadForManyToOneAndOneToOneOwner, and
loadForOneToManyAndOneToOneNotOwner, the new code silently skips any junction/join column whose
referencedColumn is undefined via if (!referenced) return. If a column is skipped, the alias
is never added to fieldsToMetadata and never selected, so the raw result rows will be missing that
column and entity-to-relation matching in loadManyToManyRelationIdsAndGroup will silently fail to
link entities.
Code

src/query-builder/RelationIdLoader.ts[R271-272]

+            const referenced = column.referencedColumn
+            if (!referenced) return
Evidence
The original code used the non-null assertion column.referencedColumn! (implying it was always
expected to be set). The new code adds if (!referenced) return in three places (lines 271-272,
285-286, 528-529, 688-689). If referencedColumn is undefined for any column, the SELECT for that
column is silently omitted. The matching logic in loadManyToManyRelationIdsAndGroup (lines
155-202) looks up relation IDs by the alias built from `column.entityMetadata.name + '_' +
column.propertyPath`, which will be absent from the result set, causing every entity to appear
unmatched and all relations to be set to empty arrays. The metadata builder always sets
referencedColumn for junction and join columns (JunctionEntityMetadataBuilder lines 90-130,
RelationJoinColumnBuilder line 253), so the guard is defensive but the silent skip is dangerous.

src/query-builder/RelationIdLoader.ts[271-272]
src/query-builder/RelationIdLoader.ts[285-286]
src/metadata-builder/JunctionEntityMetadataBuilder.ts[90-130]

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

## Issue description
When `column.referencedColumn` is `undefined`, the new code silently skips adding the column to the SELECT list and to `fieldsToMetadata`. This causes the raw query to omit the column, and the subsequent entity-matching logic in `loadManyToManyRelationIdsAndGroup` will fail to link any entities, returning empty relations without any error.

## Issue Context
- The metadata builder always sets `referencedColumn` for junction and join columns, so `undefined` should never occur in practice.
- The original code used `column.referencedColumn!` (non-null assertion), indicating the developer expected it to always be set.
- Silently skipping breaks the invariant that all required columns are selected.

## Fix Focus Areas
- src/query-builder/RelationIdLoader.ts[271-272] — `loadForManyToMany` columns loop
- src/query-builder/RelationIdLoader.ts[285-286] — `loadForManyToMany` inverseColumns loop
- src/query-builder/RelationIdLoader.ts[528-529] — `loadForManyToOneAndOneToOneOwner` joinColumns loop
- src/query-builder/RelationIdLoader.ts[688-689] — `loadForOneToManyAndOneToOneNotOwner` joinColumns loop

Replace the silent `return` with a thrown error (e.g., `throw new TypeORMError(...)`) or keep the non-null assertion to preserve the original contract and surface bugs early.

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


4. Eager chain keyed by entity name only 🐞 Bug ✓ Correctness
Description
The eagerLoadChain set is keyed by relation.inverseEntityMetadata.name, so two distinct eager
relations on the same query builder that both point to the same entity type (e.g., createdBy: User
and updatedBy: User) will cause the second relation to be silently skipped after the first is
processed.
Code

src/query-builder/SelectQueryBuilder.ts[R3637-3640]

+                    if (relation.isEager) {
+                        const targetEntity = relation.inverseEntityMetadata.name
+                        if (this.eagerLoadChain.has(targetEntity)) return
+                    }
Evidence
In executeEntitiesAndRawResults (SelectQueryBuilder.ts lines 3637-3640), when iterating
this.relationMetadatas, the code checks this.eagerLoadChain.has(targetEntity) where
targetEntity = relation.inverseEntityMetadata.name. If two eager relations on the same entity both
point to the same target entity type (e.g., createdBy and updatedBy both targeting User),
after the first relation is processed the chain will contain User (added at line 3657 for the
parent entity, not the target). However, the check at line 3638-3639 fires on the *target* entity
name, not the source. So if the parent entity itself is named User and a child relation also
targets User, the second relation is dropped. More concretely: if entity A has two eager ManyToOne
relations both pointing to entity B, after loading the first relation the chain for the child query
builder will contain A (line 3657), but the check at line 3638 looks for B in the chain. This
specific scenario is safe. However, the chain is populated with the *source* entity name (line 3657:
relation.entityMetadata.name) but checked against the *target* entity name (line 3638:
relation.inverseEntityMetadata.name). In a cycle A→B→A, when processing B's eager relation back to
A, the chain contains A (the source of the original query) and the check correctly finds A as
the target. But in a non-cycle scenario where A has two eager relations to B, the chain for the
second relation's child builder will contain A, and the check for B will not find it, so both
relations load correctly. The actual risk is when the *same* entity appears as both source and
target in the chain due to self-referencing eager relations: if entity A has an eager
self-reference, the chain will contain A after the first level, and the second level will
correctly stop. This is the intended behavior. The finding is less severe than initially assessed
but the naming is confusing and could lead to future bugs.

src/query-builder/SelectQueryBuilder.ts[3637-3640]
src/query-builder/SelectQueryBuilder.ts[3652-3658]

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 `eagerLoadChain` set stores entity names (strings). The cycle-detection check at line 3638-3639 uses `relation.inverseEntityMetadata.name` (the target entity name), while the chain is populated at line 3657 with `relation.entityMetadata.name` (the source entity name). This asymmetry means the check is: 'has the *target* entity already appeared as a *source* in the chain?' which is the correct cycle-detection logic for A→B→A cycles. However, if two different eager relations on the same entity both point to the same target entity type (e.g., `createdBy: User` and `updatedBy: User`), after the first relation's child query builder adds the parent entity name to its chain, the second relation's child builder also adds the parent entity name. Neither child builder will have the target entity name in its chain, so both load correctly. The real risk is that the entity-name key is not unique enough: two entities in different schemas or with the same class name but different targets could collide. Consider keying by a fully-qualified identifier (e.g., `entityMetadata.tableName` or the entity target constructor reference) instead of just `name`.

## Issue Context
- Cycle detection: `src/query-builder/SelectQueryBuilder.ts[3637-3640]`
- Chain population: `src/query-builder/SelectQueryBuilder.ts[3652-3658]`

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3637-3640]
- src/query-builder/SelectQueryBuilder.ts[3652-3658]

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


5. Raw hydration uses alias as lookup key 🐞 Bug ⛯ Reliability
Description
The new executeAndHydrateRaw method in RelationIdLoader looks up column metadata by the raw
result key using fieldsToMetadata.get(key), but some database drivers (e.g., PostgreSQL) return
column aliases in lowercase regardless of how they were specified, while DriverUtils.buildAlias
may produce mixed-case aliases, causing the map lookup to miss and leaving values un-hydrated.
Code

src/query-builder/RelationIdLoader.ts[R783-797]

+            .then((result) => {
+                result.forEach((data) => {
+                    Object.keys(data).forEach((key) => {
+                        const column = fieldsToMetadata.get(key)
+                        if (column) {
+                            data[key] =
+                                this.dataSource.driver.prepareHydratedValue(
+                                    data[key],
+                                    column,
+                                )
+                        }
+                    })
+                })
+                return result
+            })
Evidence
In executeAndHydrateRaw (RelationIdLoader.ts lines 783-797), the code iterates Object.keys(data)
and calls fieldsToMetadata.get(key). The keys in fieldsToMetadata are built by
DriverUtils.buildAlias (e.g., lines 274-280) which may produce mixed-case strings. However,
PostgreSQL lowercases all unquoted identifiers in query results, so the raw result keys will be
lowercase while the map keys may be mixed-case. This means fieldsToMetadata.get(key) will return
undefined for every column, and prepareHydratedValue will never be called. The consequence is
that boolean, date, and UUID columns returned as raw strings will not be converted to their proper
JavaScript types, causing type mismatches in compareEntityValue and potentially breaking
entity-to-relation matching.

src/query-builder/RelationIdLoader.ts[783-797]
src/query-builder/RelationIdLoader.ts[274-280]

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

## Issue description
`executeAndHydrateRaw` builds `fieldsToMetadata` with keys produced by `DriverUtils.buildAlias`, which may be mixed-case. PostgreSQL and some other drivers return raw result column names in lowercase. The `fieldsToMetadata.get(key)` lookup will miss when the raw key casing differs from the stored key, so `prepareHydratedValue` is never called and values remain as raw database strings.

## Issue Context
- Hydration helper: `src/query-builder/RelationIdLoader.ts[772-798]`
- Alias building: `src/query-builder/RelationIdLoader.ts[274-280]`
- The existing `loadManyToManyRelationIdsAndGroup` matching logic also uses `DriverUtils.buildAlias` for lookup keys and compares against raw result keys, so the same normalization approach used there should be applied here.

## Fix Focus Areas
- src/query-builder/RelationIdLoader.ts[783-797] — normalize `key` (e.g., `key.toLowerCase()`) before calling `fieldsToMetadata.get(key)`, and store keys in `fieldsToMetadata` in the same normalized form when they are inserted (lines 281, 297, 521, 540, 681, 698)

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


Grey Divider

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

Grey Divider

Qodo Logo

@alumni
alumni merged commit 5797d97 into typeorm:master Mar 23, 2026
75 of 78 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Mar 23, 2026
@SharkSharp

Copy link
Copy Markdown
Contributor Author

Hi @pkuczynski, thank you for the time and effort you put into reviewing and improving this PR.

I reviewed the changes and noticed two points that I think are worth considering:

The way the tests were originally implemented reflects the nature of the issue: eager loading was working, but not in the correct way. I considered it important to use a spy to map the internal flow so the test would fail without the fix and pass after the fix. Looking at the new test, I believe this behavior may no longer be covered, and the maintainers can confirm whether this change introduces any issues.

Regarding the eager-load loop check, at the time I was not able to reproduce a case where the loop actually occurred, so I assumed there was already some internal process preventing those scenarios. For that reason, I did not prioritize implementing an additional safeguard. I still believe there is another safeguard preventing the loop; if I find it, I will add a comment documenting it.

I’m currently working on a robust project running on a fork with these fixes. I will apply the latest changes there and test them in staging to verify whether any unusual behavior appears. If anything remaining comes up, I’ll open a follow-up PR referencing this one and addressing the issues found.

Thanks again for your attention. Should any further changes or fixes be needed, I remain available to help, please feel free to reach out.

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

Development

Successfully merging this pull request may close these issues.

Eager relations do not respect relationLoadStrategy

5 participants