Repository navigation
fix: prevent eager-loaded entities from overwriting manual relations - #11267
Conversation
…ting manual relations The issue was caused by the way TypeORM processing queries. For each join, it checks if the join for that table exists. However, if the join has a condition, it will always add the join, even if a previous join for the same table already exists. In the case of eager loading, TypeORM creates its own join, and since it has a DeleteDateColumn, an additional condition is added to the join (checking for a null DeletedDate). This newly added join does not match the manually specified join, and if the manual relation had additional nested fields that were not part of the eager load, those fields would be overwritten. This fix addresses the issue by merging the manually requested relations with the eager-loaded data, preserving the complete details of the manual relations. Closes: typeorm#11265
WalkthroughThis PR fixes a bug in eager-relation handling by modifying the merge strategy in RelationMetadata to preserve manually requested nested relations. Instead of direct assignment, non-embedded entity values are now merged using OrmUtils.mergeDeep, preventing eager-loaded relations from overwriting nested relation data. Test cases updated to verify the fix. Changes
Sequence DiagramsequenceDiagram
participant App as Application
participant RelMeta as RelationMetadata<br/>(setEntityValue)
participant Entity as Target Entity
participant OrmUtils as OrmUtils
rect rgb(220, 240, 255)
note over RelMeta,Entity: Old Flow (Direct Assignment)
App->>RelMeta: setEntityValue(entity, value)
RelMeta->>Entity: entity[prop] = value
note over Entity: ❌ Overwrites nested data
end
rect rgb(240, 255, 240)
note over RelMeta,Entity: New Flow (Merge Strategy)
App->>RelMeta: setEntityValue(entity, value)
alt entity[prop] is object
RelMeta->>OrmUtils: mergeDeep(entity[prop], value)
OrmUtils->>Entity: Merged result
note over Entity: ✓ Preserves nested relations
else entity[prop] is primitive
RelMeta->>Entity: entity[prop] = value
note over Entity: Direct assignment
end
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes The changes are focused and follow a consistent pattern (merge vs. assign logic), with straightforward test additions. However, understanding the implications of the merge strategy for relation handling requires some domain context. Possibly related issues
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
commit: |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/metadata/RelationMetadata.ts (1)
483-488: Docblock drift: remove stale “merge” parameter reference.The comment mentions a
mergeflag that doesn’t exist. Update to reflect unconditional (scoped) merge behavior.- * - * If merge is set to true, it merges given value into currently + * Merges existing relation object fields from the entity when applicable (to‑one relations), + * then assigns the final value to the property.test/github-issues/11265/issue-11265.ts (1)
48-56: Nit: fix comment to reflect entity name.Rename “Retrieve user…” to “Retrieve parent…” for clarity.
- // Retrieve user with manually specified nested relation + // Retrieve parent with manually specified nested relation
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/metadata/RelationMetadata.ts(1 hunks)test/github-issues/11265/entity/parent.ts(1 hunks)test/github-issues/11265/entity/relationEntity.ts(1 hunks)test/github-issues/11265/entity/relationNestedEntity.ts(1 hunks)test/github-issues/11265/issue-11265.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
test/github-issues/11265/entity/relationNestedEntity.ts (3)
test/github-issues/11265/entity/parent.ts (1)
Entity(4-11)test/github-issues/11265/entity/relationEntity.ts (1)
Entity(8-18)src/decorator/columns/PrimaryGeneratedColumn.ts (1)
PrimaryGeneratedColumn(55-119)
src/metadata/RelationMetadata.ts (1)
src/util/ObjectUtils.ts (1)
ObjectUtils(3-82)
test/github-issues/11265/issue-11265.ts (1)
test/utils/test-utils.ts (3)
createTestingConnections(388-482)reloadTestingDatabases(500-505)closeTestingConnections(487-495)
test/github-issues/11265/entity/relationEntity.ts (5)
test/github-issues/11265/entity/parent.ts (1)
Entity(4-11)test/github-issues/11265/entity/relationNestedEntity.ts (1)
Entity(3-7)src/decorator/columns/PrimaryGeneratedColumn.ts (1)
PrimaryGeneratedColumn(55-119)src/decorator/columns/DeleteDateColumn.ts (1)
DeleteDateColumn(9-18)src/decorator/relations/ManyToOne.ts (1)
ManyToOne(33-77)
test/github-issues/11265/entity/parent.ts (4)
test/github-issues/11265/entity/relationEntity.ts (1)
Entity(8-18)test/github-issues/11265/entity/relationNestedEntity.ts (1)
Entity(3-7)src/decorator/columns/PrimaryGeneratedColumn.ts (1)
PrimaryGeneratedColumn(55-119)src/decorator/relations/ManyToOne.ts (1)
ManyToOne(33-77)
🔇 Additional comments (4)
test/github-issues/11265/entity/relationNestedEntity.ts (1)
3-7: LGTM.Minimal entity for nesting; appropriate for the scenario.
test/github-issues/11265/entity/parent.ts (1)
9-11: LGTM.Eager relation on ParentEntity correctly models the issue.
test/github-issues/11265/entity/relationEntity.ts (1)
13-18: LGTM.DeleteDateColumn + nested relation nicely reproduces the original bug.
src/metadata/RelationMetadata.ts (1)
523-526: Guard merge: restrict ObjectUtils.assign to to‑one, non‑lazy plain‑object relationsFile: src/metadata/RelationMetadata.ts (lines 523-526)
Risk: merging when value is undefined/primitive, lazy (Promise) or to‑many (array) can throw or corrupt/duplicate relation data — only merge plain objects for to‑one, non‑lazy relations.
Apply:
- if (ObjectUtils.isObject(entity[propertyName])) - ObjectUtils.assign(value, entity[propertyName]) - entity[propertyName] = value + // Merge existing manual relation fields into the incoming value only for to‑one relations. + if ( + !this.isOneToMany && + !this.isManyToMany && + !this.isLazy && + ObjectUtils.isObject(value) && + ObjectUtils.isObject(entity[propertyName]) + ) { + ObjectUtils.assign(value, entity[propertyName]) + } + entity[propertyName] = valueTests to add:
- many-to-many / one-to-many assignments — ensure no duplication or array-index/length corruption.
- lazy relation property — ensure a Promise is not merged into the target object.
gioboa
left a comment
There was a problem hiding this comment.
Hi @LeviHeber, thanks for this great PR, can you fix up the sap tests please?
gioboa
left a comment
There was a problem hiding this comment.
Thanks for your help @LeviHeber
|
i left the test to be |
gioboa
left a comment
There was a problem hiding this comment.
Yes, remove the .only please
|
I removed the |
That sounds possibly related to #11653 which has been fixed now. Tests are passing in this PR. |
|
I made the following fixes:
|
|
Is there anything else that needs to be done to move forward? |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts (1)
27-28: Consider makingnestedProfileoptional for type safety.The
nestedProfilefield is declared as non-optional but won't be populated in all test scenarios (e.g., in the first test case at lines 65-131). While this works in practice since it's test code, making it optional would better reflect its usage.Apply this diff to improve type accuracy:
- @ManyToOne(() => Profile) - nestedProfile: Profile + @ManyToOne(() => Profile) + nestedProfile?: Profiletest/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts (1)
150-187: Excellent test coverage for the bug fix!The test case comprehensively validates that manually requested nested relations are preserved when DeleteDateColumn is present. The flow is clear: create nested relation, link it, retrieve with manual relations specification, and assert preservation.
One minor enhancement to consider: the test currently asserts that the manually requested
nestedProfileis preserved, but it could also verify that the eager-loadeduser.profilerelation is still correctly loaded alongside it (e.g.,retrievedEditor!.user.profile.about.should.equal("I cut trees!")). This would provide additional confidence that the merge doesn't break eager relations.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/metadata/RelationMetadata.ts(2 hunks)test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts(3 hunks)test/functional/relations/eager-relations/basic-eager-relations/entity/Profile.ts(1 hunks)test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts(2 hunks)
✅ Files skipped from review due to trivial changes (1)
- test/functional/relations/eager-relations/basic-eager-relations/entity/Profile.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/metadata/RelationMetadata.ts
🔇 Additional comments (3)
test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts (1)
7-7: LGTM!The combined import statement is clean and follows TypeScript conventions.
test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts (2)
107-107: LGTM!Correctly adds the expected
deletedAt: nullvalue for the eagerly loaded author relation, reflecting the newDeleteDateColumnon the User entity.
121-121: LGTM!Correctly adds the expected
deletedAt: nullvalue for the eagerly loaded editor.user relation, consistent with the DeleteDateColumn addition.
gioboa
left a comment
There was a problem hiding this comment.
May I ask you to solve the conflicts please?
Thanks for your help @LeviHeber
PR Code Suggestions ✨Latest suggestions up to 4e2bcf2
Previous suggestionsSuggestions up to commit 0ef98b3
Suggestions up to commit 3539087
Suggestions up to commit 28c9e7d
Suggestions up to commit ac46664
Suggestions up to commit 877fda4
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
All the requested changes are now implemented.
|
I think the issue that we have could possibly be a bit earlier, when we build the query. It seems we select the user twice - maybe once because it's an eagerly loaded relation and another time because it was requested by the user. In the test we have: await connection.manager.findOne(
Editor,
{
where: { userId: 1 },
relations: {
user: {
nestedProfile: true,
},
},
},
)which generates the query: SELECT
"Editor"."userId" AS "Editor_userId",
"Editor"."postId" AS "Editor_postId",
"Editor__Editor_user"."id" AS "Editor__Editor_user_id",
"Editor__Editor_user"."firstName" AS "Editor__Editor_user_firstName",
"Editor__Editor_user"."lastName" AS "Editor__Editor_user_lastName",
"Editor__Editor_user"."deletedAt" AS "Editor__Editor_user_deletedAt",
"Editor__Editor_user"."profileId" AS "Editor__Editor_user_profileId",
"Editor__Editor_user"."nestedProfileId" AS "Editor__Editor_user_nestedProfileId",
"Editor__Editor_user__Editor__Editor_user_nestedProfile"."id" AS "Editor__Editor_user__Editor__Editor_user_nestedProfile_id",
"Editor__Editor_user__Editor__Editor_user_nestedProfile"."about" AS "Editor__Editor_user__Editor__Editor_user_nestedProfile_about",
"Editor__Editor_user__Editor__Editor_user_profile"."id" AS "Editor__Editor_user__Editor__Editor_user_profile_id",
"Editor__Editor_user__Editor__Editor_user_profile"."about" AS "Editor__Editor_user__Editor__Editor_user_profile_about",
"Editor__user"."id" AS "Editor__user_id",
"Editor__user"."firstName" AS "Editor__user_firstName",
"Editor__user"."lastName" AS "Editor__user_lastName",
"Editor__user"."deletedAt" AS "Editor__user_deletedAt",
"Editor__user"."profileId" AS "Editor__user_profileId",
"Editor__user"."nestedProfileId" AS "Editor__user_nestedProfileId",
"Editor__user__profile"."id" AS "Editor__user__profile_id",
"Editor__user__profile"."about" AS "Editor__user__profile_about"
FROM
"editor" "Editor"
LEFT JOIN "user" "Editor__Editor_user" ON "Editor__Editor_user"."id" = "Editor"."userId"
AND ("Editor__Editor_user"."deletedAt" IS NULL)
LEFT JOIN "profile" "Editor__Editor_user__Editor__Editor_user_nestedProfile" ON "Editor__Editor_user__Editor__Editor_user_nestedProfile"."id" = "Editor__Editor_user"."nestedProfileId"
LEFT JOIN "profile" "Editor__Editor_user__Editor__Editor_user_profile" ON "Editor__Editor_user__Editor__Editor_user_profile"."id" = "Editor__Editor_user"."profileId"
LEFT JOIN "user" "Editor__user" ON "Editor__user"."id" = "Editor"."userId"
AND ("Editor__user"."deletedAt" IS NULL)
LEFT JOIN "profile" "Editor__user__profile" ON "Editor__user__profile"."id" = "Editor__user"."profileId"
WHERE
((("Editor"."userId" = 1)))
AND (
"Editor"."userId" = 1
AND "Editor"."postId" = 1
)We have both I'll check tomorrow to see if this is intended. |
|
We'll create a separate issue for the extra things in the join so we don't block this. Later edit: created #11823. |
…ypeorm#11267) Co-authored-by: Lucian Mocanu <[email protected]> Co-authored-by: Giorgio Boa <[email protected]>
…ypeorm#11267) Co-authored-by: Lucian Mocanu <[email protected]> Co-authored-by: Giorgio Boa <[email protected]>
Description of change
The issue was caused by the way TypeORM processing queries. For each join, it checks if the join for that table exists. However, if the join has a condition, it will always add the join, even if a previous join for the same table already exists.
In the case of eager loading, TypeORM creates its own join, and since it has a DeleteDateColumn, an additional condition is added to the join (checking for a null DeletedDate). This newly added join does not match the manually specified join, and if the manual relation had additional nested fields that were not part of the eager load, those fields would be overwritten.
This fix addresses the issue by merging the manually requested relations with the eager-loaded data, preserving the complete details of the manual relations.
In issue #10426 , the same case was described, where there are 2 joins to the same table,
which causes performance issues.
The current fix does not change the join process and leaves both joins as they were,
but only fixes the consequences that were created as a result of it in the object creation,
because this is a consequence that is relevant both to this case and to other cases.
Unrelated, it should check how to deal with the problem of having 2 joins, for performance reasons.
Fixes: #11265
Fixes: #10812
Fixes: #9774
Fixes: #9581
Pull-Request Checklist
masterbranchnpm run formatto apply prettier formattingnpm run testpasses with this changeFixes #0000