Skip to content

perf(relations)!: use inner join for non-nullable ManyToOne and OneToOne relations - #12064

Merged
pkuczynski merged 12 commits into
typeorm:masterfrom
chunghyunleeme:feat/nullable-inner-join
Mar 20, 2026
Merged

pkuczynski merged 12 commits into
typeorm:masterfrom
chunghyunleeme:feat/nullable-inner-join

Conversation

@chunghyunleeme

Copy link
Copy Markdown
Contributor

Summary

  • Use INNER JOIN instead of LEFT JOIN when a relation is explicitly marked as nullable: false, matching JPA's @JoinColumn(nullable = false) behavior
  • This is semantically correct since the related entity is guaranteed to exist, and allows the DB optimizer to produce more efficient query plans
  • Relations with nullable: true (the default) continue using LEFT JOIN, preserving full backward compatibility

Changes

  • SelectQueryBuilder.ts (4 locations): type: "left" → type: relation.isNullable ? "left" : "inner" in buildRelations(), buildEagerRelations(), buildOrder(), buildWhere()
  • FindOptionsUtils.ts (3 locations): conditional leftJoin/innerJoin and leftJoinAndSelect/innerJoinAndSelect based on relation.isNullable, plus duplicate join validation fix for INNER joins
  • Test: added nullable: false eager relation entity and test case verifying INNER JOIN generation

Test plan

  • Existing eager-relations tests pass (backward compatibility)
  • New test verifies generated SQL contains INNER JOIN for nullable: false relations
  • New test verifies data loads correctly with INNER JOIN
  • Full test suite passes (2494 passing)

Like JPA's @joincolumn(nullable = false) behavior, use INNER JOIN when
a relation is explicitly marked as nullable: false. This is semantically
correct since the related entity is guaranteed to exist, and allows the
DB optimizer to produce more efficient query plans. Relations with
nullable: true (the default) continue using LEFT JOIN, preserving
backward compatibility.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Use INNER JOIN for nullable=false relations instead of LEFT JOIN

✨ Enhancement 🧪 Tests

Grey Divider

Walkthroughs

Description
• Use INNER JOIN instead of LEFT JOIN for nullable: false relations
• Applied across SelectQueryBuilder.ts (4 locations) and FindOptionsUtils.ts (3 locations)
• Duplicate join detection updated to accept both LEFT and INNER joins
• Added test entity field and test case verifying INNER JOIN for non-nullable eager relations
Diagram
flowchart LR
  A["Relation metadata"]
  B["relation.isNullable = true"]
  C["relation.isNullable = false"]
  D["LEFT JOIN"]
  E["INNER JOIN"]
  A -- "check nullability" --> B
  A -- "check nullability" --> C
  B -- "generates" --> D
  C -- "generates" --> E
Loading

Grey Divider

File Changes

1. src/find-options/FindOptionsUtils.ts ✨ Enhancement +17/-3

Conditional LEFT/INNER join based on relation nullability

• Switch leftJoinAndSelect to innerJoinAndSelect when relation.isNullable is false
• Switch leftJoin to innerJoin when relation.isNullable is false
• Update duplicate join detection to accept both LEFT and INNER join directions

src/find-options/FindOptionsUtils.ts


2. src/query-builder/SelectQueryBuilder.ts ✨ Enhancement +6/-4

Use INNER JOIN type for non-nullable relations in query builder

• Replace hardcoded type: "left" with type: relation.isNullable ? "left" : "inner" in
 buildRelations()
• Same conditional applied in buildEagerRelations(), buildOrder(), and buildWhere()

src/query-builder/SelectQueryBuilder.ts


3. test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts 🧪 Tests +38/-0

Add tests for INNER JOIN on nullable=false eager relations

• Assign requiredAuthor in prepareData setup
• Add expected requiredAuthor field to existing result assertion
• Add new test verifying INNER JOIN is used for nullable: false eager relation
• Verify LEFT JOIN is still used for nullable relation and data loads correctly

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts


View more (1)
4. test/functional/relations/eager-relations/basic-eager-relations/entity/Post.ts 🧪 Tests +3/-0

Add non-nullable eager relation field to Post entity

• Add requiredAuthor field as a ManyToOne relation with eager: true and nullable: false

test/functional/relations/eager-relations/basic-eager-relations/entity/Post.ts


Grey Divider

Qodo Logo

@chunghyunleeme chunghyunleeme changed the title feat: use INNER JOIN for nullable=false relations feat: use inner join for nullable=false relations Mar 3, 2026
@chunghyunleeme chunghyunleeme changed the title feat: use inner join for nullable=false relations feat: use inner join for non-nullable relations Mar 3, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Mar 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Nested INNER JOIN filters rows ☑ 🐞 Bug ✓ Correctness
Description
When an optional relation is loaded via LEFT JOIN, the code may still emit INNER JOINs for its
non-nullable eager/nested relations, which removes base rows where the intermediate relation is
NULL. This breaks relation loading for graphs like A.optionalB (nullable) + B.requiredC
(nullable:false/eager or nested relations), where A rows with no B should still be returned.
Code

src/query-builder/SelectQueryBuilder.ts[R4099-4105]

                              this.joins.push({
-                                    type: "left",
+                                    type: this.getRelationJoinType(
+                                        eagerRelation,
+                                    ),
                                  select: true,
                                  alias: eagerRelationJoinAlias,
                                  parentAlias: joinAlias,
Evidence
buildRelations LEFT-joins nullable relations, then recurses into sub-relations using the joined
alias as the new parent alias; join type for those sub-relations is computed independently and can
become INNER. buildEagerRelations similarly joins eager relations off the joined alias and can
choose INNER based only on the eager relation’s nullability. FindOptionsUtils.joinEagerRelations
is recursive as well and chooses INNER for non-nullable relations without checking whether the
current alias was produced by a LEFT join. SQL is emitted as a flat sequence of joins (`<direction>
JOIN ... ON ...), so LEFT JOIN B ... INNER JOIN C ON ...B... eliminates rows where B` is NULL.

src/query-builder/SelectQueryBuilder.ts[3988-4035]
src/query-builder/SelectQueryBuilder.ts[4082-4109]
src/find-options/FindOptionsUtils.ts[79-102]
src/find-options/FindOptionsUtils.ts[306-389]
src/query-builder/SelectQueryBuilder.ts[2352-2418]

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

## Issue description
INNER vs LEFT join is chosen per relation (`nullable:false` =&amp;amp;gt; INNER) without considering whether the *parent alias* was produced by a LEFT JOIN (because the parent relation was nullable). In SQL, an INNER JOIN off a LEFT-joined alias filters out rows where the parent alias is NULL, so loading nested/eager relations can incorrectly drop base entities.
## Issue Context
This can happen in both:
- `SelectQueryBuilder.buildRelations()` recursion for nested `relations: { a: { b: true } }`
- `SelectQueryBuilder.buildEagerRelations()` (eager relations of a joined relation)
- `FindOptionsUtils.joinEagerRelations()` recursion (global eager loading)
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3950-4141]
- src/find-options/FindOptionsUtils.ts[79-102]
- src/find-options/FindOptionsUtils.ts[306-389]
- src/query-builder/SelectQueryBuilder.ts[2352-2418]
## What to change
1. Ensure join type selection is *context-aware*:
- If the current parent alias was introduced via a LEFT join (i.e., the parent relation was nullable or otherwise forced-left), then all descendant joins off that alias must also be LEFT to avoid filtering NULL-extended rows.
- Only allow INNER joins when the entire ancestor chain up to the main entity is INNER/base.
2. Implement this by propagating a `parentJoinType` / `forceLeftJoin` flag through:
- `buildRelations()` recursion
- `buildEagerRelations()` recursion
- `FindOptionsUtils.joinEagerRelations()` recursion (derive parent join direction from the existing `joinAttributes` entry for the current alias, if any).
3. Add a regression test:
- Entity `A` has `optionalB` (nullable true).
- Entity `B` has `requiredC` (nullable false) as an eager relation (or requested nested relation).
- Query loads `optionalB` and verify rows with `optionalB = NULL` are still returned.

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


2. Soft-delete rows filtered ☑ 🐞 Bug ✓ Correctness
Description
Using INNER JOIN for nullable: false owning relations will now exclude parent entities when the
related row is soft-deleted, because TypeORM appends joinedAlias. IS NULL into the JOIN ON clause.
Previously, a LEFT JOIN would still return the parent row and just hydrate the relation as null.
Code

src/query-builder/SelectQueryBuilder.ts[R3981-3985]

+                            type:
+                                !relation.isNullable &&
+                                relation.isWithJoinColumn
+                                    ? "inner"
+                                    : "left",
Evidence
The PR changes join type selection to inner for non-nullable owning relations in both the
SelectQueryBuilder find-options join plan and in FindOptionsUtils. Separately, SelectQueryBuilder’s
join builder automatically appends a soft-delete predicate (. IS NULL) into the join condition
when withDeleted is not enabled; this predicate is emitted in the JOIN’s ON clause. With INNER
JOIN, that ON predicate filters out the entire parent row when the related row is soft-deleted,
whereas with LEFT JOIN it would only null out the joined columns and still keep the parent row.

src/query-builder/SelectQueryBuilder.ts[3968-3986]
src/find-options/FindOptionsUtils.ts[206-216]
src/query-builder/SelectQueryBuilder.ts[2157-2167]
src/query-builder/SelectQueryBuilder.ts[2361-2418]
docs/docs/guides/8-migration-v1.md[428-448]

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

## Issue description
`nullable: false` relations are now loaded with `INNER JOIN`. TypeORM automatically appends `joinedAlias.&amp;amp;amp;amp;amp;amp;amp;lt;deleteDateColumn&amp;amp;amp;amp;amp;amp;amp;gt; IS NULL` to join conditions when `withDeleted` is not set. With an `INNER JOIN`, this turns soft-deleted related rows into a filter that removes the parent row from results (previously `LEFT JOIN` preserved the parent row and just returned the relation as `null`).
## Issue Context
This affects common setups where the related entity has a `@DeleteDateColumn` (soft delete). Even with a non-nullable FK, soft-delete is not a data-integrity violation; it’s expected state, so dropping parent rows is a behavior regression for many users.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3968-3986]
- src/find-options/FindOptionsUtils.ts[206-216]
- src/query-builder/SelectQueryBuilder.ts[2157-2167]
- src/query-builder/SelectQueryBuilder.ts[2361-2418]
- docs/docs/guides/8-migration-v1.md[428-448]
## Suggested fix approach
- When choosing INNER vs LEFT join for `nullable:false` relations, also consider soft-delete behavior:
- If the destination metadata has `deleteDateColumn` and `withDeleted` is **false**, keep using `LEFT JOIN` (or otherwise preserve the old semantics).
- Alternatively, if the new filtering behavior is intended, explicitly document this in the migration guide as an additional breaking case and add a regression test covering a soft-deleted required relation.

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


3. Wrong INNER JOIN scope ☑ 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder switches to INNER JOIN purely based on relation.isNullable, even for relation
types that don't have a join column (e.g., OneToMany/ManyToMany/OneToOne inverse). If users set
nullable: false on those relations, queries can start filtering out parent rows when the relation
is empty, causing silent data loss.
Code

src/query-builder/SelectQueryBuilder.ts[R4155-4156]

+                            type: relation.isNullable ? "left" : "inner",
                 select: true,
Evidence
nullable is a generic RelationOptions flag accepted by decorators like OneToMany/ManyToMany, and
RelationMetadata.isNullable is derived directly from args.options.nullable. Those relation types
often have no join column on the current table (see isWithJoinColumn), so nullable:false does
not imply the related row must exist; however the new code will generate INNER JOINs and filter out
rows.

src/query-builder/SelectQueryBuilder.ts[4153-4157]
src/query-builder/SelectQueryBuilder.ts[4396-4404]
src/query-builder/SelectQueryBuilder.ts[4714-4722]
src/decorator/options/RelationOptions.ts[20-24]
src/decorator/relations/OneToMany.ts[14-18]
src/decorator/relations/ManyToMany.ts[14-17]
src/metadata/RelationMetadata.ts[327-328]
src/metadata/RelationMetadata.ts[197-200]

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` uses `relation.isNullable ? &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;left&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; : &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;inner&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;` for joins created by find-options relation handling. Since `nullable` is allowed on relation types without join columns (e.g., OneToMany/ManyToMany/OneToOne inverse), setting `nullable:false` on those can incorrectly produce INNER JOINs and filter out parent rows.
### Issue Context
Use INNER JOIN only when `relation.isWithJoinColumn` (or equivalently `relation.isManyToOne || (relation.isOneToOne &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; relation.isOneToOneOwner)`) and `relation.isNullable === false`.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4153-4167]
- src/query-builder/SelectQueryBuilder.ts[4264-4273]
- src/query-builder/SelectQueryBuilder.ts[4393-4404]
- src/query-builder/SelectQueryBuilder.ts[4711-4722]

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



Remediation recommended

4. Duplicated join-type logic ☑ 🐞 Bug ⚙ Maintainability
Description
The “INNER join iff non-nullable + owns join column + (no soft-delete or withDeleted)” rule is
implemented multiple times (including twice inside FindOptionsUtils) instead of being centralized.
This increases the risk that future changes/fixes update one path (e.g., QueryBuilder find options)
but not another (e.g., eager/tree relation joining), leading to inconsistent SQL generation.
Code

src/find-options/FindOptionsUtils.ts[R321-336]

+                if (
+                    !relation.isNullable &&
+                    relation.isWithJoinColumn &&
+                    (!relation.inverseEntityMetadata.deleteDateColumn ||
+                        qb.expressionMap.withDeleted)
+                ) {
+                    qb.innerJoin(
+                        alias + "." + relation.propertyPath,
+                        relationAlias,
+                    )
+                } else {
+                    qb.leftJoin(
+                        alias + "." + relation.propertyPath,
+                        relationAlias,
+                    )
+                }
Evidence
FindOptionsUtils contains two separate inline implementations of the same rule
(applyRelationsRecursively and joinEagerRelations). SelectQueryBuilder extracted the same policy
into getRelationJoinType(), but FindOptionsUtils does not reuse it, so the policy can drift across
call paths over time.

src/find-options/FindOptionsUtils.ts[206-219]
src/find-options/FindOptionsUtils.ts[295-337]
src/query-builder/SelectQueryBuilder.ts[3935-3958]

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 join-type decision policy (nullable + join-column ownership + soft-delete + withDeleted) is duplicated in multiple locations, including twice in `FindOptionsUtils`. This duplication risks future divergence where different loading paths generate different joins for the same relation configuration.
### Issue Context
`SelectQueryBuilder` already has `getRelationJoinType()`, but `FindOptionsUtils` re-implements the same condition inline for both `applyRelationsRecursively` and `joinEagerRelations`.
### Fix Focus Areas
- src/find-options/FindOptionsUtils.ts[206-219]
- src/find-options/FindOptionsUtils.ts[295-337]
- src/query-builder/SelectQueryBuilder.ts[3935-3958]
### Suggested approach
- Extract a shared helper (e.g., `getRelationJoinType(relation, withDeleted)` or `shouldUseInnerJoinForRelation(relation, withDeleted)`) in a common module.
- Use it from:
- `SelectQueryBuilder.getRelationJoinType()` (delegate to helper)
- `FindOptionsUtils.applyRelationsRecursively()`
- `FindOptionsUtils.joinEagerRelations()`
- Keep return type consistent (e.g., `&amp;amp;amp;amp;amp;#x27;inner&amp;amp;amp;amp;amp;#x27;|&amp;amp;amp;amp;amp;#x27;left&amp;amp;amp;amp;amp;#x27;`) and adapt to `FindOptionsUtils`’s uppercase `join.direction` needs where necessary.

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


5. nullable:false JOIN docs missing ☑ 📘 Rule violation ✓ Correctness
Description
This PR changes generated SQL to use INNER JOIN for relations marked nullable: false, which is a
user-visible behavior change. The existing relations docs describe nullable only as database
nullability and are not updated to mention the join-generation impact.
Code

src/query-builder/SelectQueryBuilder.ts[4155]

+                            type: relation.isNullable ? "left" : "inner",
Evidence
Compliance requires documentation updates for user-facing behavior changes. The PR explicitly
introduces conditional INNER JOIN generation based on relation.isNullable, while the relations
documentation still explains nullable only in terms of whether the relation column can be NULL,
without mentioning query join behavior.

Rule 2: Docs updated for user-facing changes
src/query-builder/SelectQueryBuilder.ts[4153-4156]
docs/docs/relations/1-relations.md[17-21]

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 PR introduces user-visible query generation behavior: relations marked `nullable: false` now use `INNER JOIN` instead of `LEFT JOIN`. Documentation for relation options currently describes `nullable` only as DB nullability and does not mention this join-generation effect.
## Issue Context
This behavior affects SQL produced by find-options/eager relation loading and can impact results (e.g., rows filtered out if the DB data violates the non-null expectation) and query plans. Users need to know that setting `nullable: false` can change joins to `INNER JOIN`.
## Fix Focus Areas
- docs/docs/relations/1-relations.md[13-25]
- docs/docs/relations/5-eager-and-lazy-relations.md[64-67]

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


6. Test join assertion weak ☑ 🐞 Bug ⛯ Reliability
Description
The new test only asserts that the SQL contains "INNER JOIN" and "LEFT JOIN" somewhere, which
doesn't prove that requiredAuthor is INNER-joined and author is LEFT-joined. Strengthening the
assertion would better prevent regressions and false positives.
Code

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[R261-266]

+                // nullable=false relation (requiredAuthor) should use INNER JOIN
+                expect(query).to.contain("INNER JOIN")
+
+                // nullable=true relation (author) should still use LEFT JOIN
+                expect(query).to.contain("LEFT JOIN")
+
Evidence
The test checks only for the presence of join keywords, not that they correspond to specific
relations; the query could include these tokens due to other joins while still joining the targeted
relations incorrectly.

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[256-266]

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 SQL assertion is too generic and may pass even if the wrong relation uses INNER vs LEFT joins.
### Issue Context
The join clauses should be validated against the target relation names (e.g., `requiredAuthor` / `requiredAuthorId` and `author` / `authorId`) or stable aliases produced by TypeORM.
### Fix Focus Areas
- test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[251-275]

ⓘ 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

Grey Divider

Previous review results

Review updated until commit c597ecd

Results up to commit N/A


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

Grey Divider
Action required
1. Nested INNER JOIN filters rows ☑ 🐞 Bug ✓ Correctness
Description
When an optional relation is loaded via LEFT JOIN, the code may still emit INNER JOINs for its
non-nullable eager/nested relations, which removes base rows where the intermediate relation is
NULL. This breaks relation loading for graphs like A.optionalB (nullable) + B.requiredC
(nullable:false/eager or nested relations), where A rows with no B should still be returned.
Code

src/query-builder/SelectQueryBuilder.ts[R4099-4105]

                               this.joins.push({
-                                    type: "left",
+                                    type: this.getRelationJoinType(
+                                        eagerRelation,
+                                    ),
                                   select: true,
                                   alias: eagerRelationJoinAlias,
                                   parentAlias: joinAlias,
Evidence
buildRelations LEFT-joins nullable relations, then recurses into sub-relations using the joined
alias as the new parent alias; join type for those sub-relations is computed independently and can
become INNER. buildEagerRelations similarly joins eager relations off the joined alias and can
choose INNER based only on the eager relation’s nullability. FindOptionsUtils.joinEagerRelations
is recursive as well and chooses INNER for non-nullable relations without checking whether the
current alias was produced by a LEFT join. SQL is emitted as a flat sequence of joins (`<direction>
JOIN ... ON ...), so LEFT JOIN B ... INNER JOIN C ON ...B... eliminates rows where B` is NULL.

src/query-builder/SelectQueryBuilder.ts[3988-4035]
src/query-builder/SelectQueryBuilder.ts[4082-4109]
src/find-options/FindOptionsUtils.ts[79-102]
src/find-options/FindOptionsUtils.ts[306-389]
src/query-builder/SelectQueryBuilder.ts[2352-2418]

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

## Issue description
INNER vs LEFT join is chosen per relation (`nullable:false` =&amp;gt; INNER) without considering whether the *parent alias* was produced by a LEFT JOIN (because the parent relation was nullable). In SQL, an INNER JOIN off a LEFT-joined alias filters out rows where the parent alias is NULL, so loading nested/eager relations can incorrectly drop base entities.
## Issue Context
This can happen in both:
- `SelectQueryBuilder.buildRelations()` recursion for nested `relations: { a: { b: true } }`
- `SelectQueryBuilder.buildEagerRelations()` (eager relations of a joined relation)
- `FindOptionsUtils.joinEagerRelations()` recursion (global eager loading)
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3950-4141]
- src/find-options/FindOptionsUtils.ts[79-102]
- src/find-options/FindOptionsUtils.ts[306-389]
- src/query-builder/SelectQueryBuilder.ts[2352-2418]
## What to change
1. Ensure join type selection is *context-aware*:
 - If the current parent alias was introduced via a LEFT join (i.e., the parent relation was nullable or otherwise forced-left), then all descendant joins off that alias must also be LEFT to avoid filtering NULL-extended rows.
 - Only allow INNER joins when the entire ancestor chain up to the main entity is INNER/base.
2. Implement this by propagating a `parentJoinType` / `forceLeftJoin` flag through:
 - `buildRelations()` recursion
 - `buildEagerRelations()` recursion
 - `FindOptionsUtils.joinEagerRelations()` recursion (derive parent join direction from the existing `joinAttributes` entry for the current alias, if any).
3. Add a regression test:
 - Entity `A` has `optionalB` (nullable true).
 - Entity `B` has `requiredC` (nullable false) as an eager relation (or requested nested relation).
 - Query loads `optionalB` and verify rows with `optionalB = NULL` are still returned.

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


2. Soft-delete rows filtered ☑ 🐞 Bug ✓ Correctness
Description
Using INNER JOIN for nullable: false owning relations will now exclude parent entities when the
related row is soft-deleted, because TypeORM appends joinedAlias. IS NULL into the JOIN ON clause.
Previously, a LEFT JOIN would still return the parent row and just hydrate the relation as null.
Code

src/query-builder/SelectQueryBuilder.ts[R3981-3985]

+                            type:
+                                !relation.isNullable &&
+                                relation.isWithJoinColumn
+                                    ? "inner"
+                                    : "left",
Evidence
The PR changes join type selection to inner for non-nullable owning relations in both the
SelectQueryBuilder find-options join plan and in FindOptionsUtils. Separately, SelectQueryBuilder’s
join builder automatically appends a soft-delete predicate (. IS NULL) into the join condition
when withDeleted is not enabled; this predicate is emitted in the JOIN’s ON clause. With INNER
JOIN, that ON predicate filters out the entire parent row when the related row is soft-deleted,
whereas with LEFT JOIN it would only null out the joined columns and still keep the parent row.

src/query-builder/SelectQueryBuilder.ts[3968-3986]
src/find-options/FindOptionsUtils.ts[206-216]
src/query-builder/SelectQueryBuilder.ts[2157-2167]
src/query-builder/SelectQueryBuilder.ts[2361-2418]
docs/docs/guides/8-migration-v1.md[428-448]

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

## Issue description
`nullable: false` relations are now loaded with `INNER JOIN`. TypeORM automatically appends `joinedAlias.&amp;amp;amp;amp;amp;amp;lt;deleteDateColumn&amp;amp;amp;amp;amp;amp;gt; IS NULL` to join conditions when `withDeleted` is not set. With an `INNER JOIN`, this turns soft-deleted related rows into a filter that removes the parent row from results (previously `LEFT JOIN` preserved the parent row and just returned the relation as `null`).
## Issue Context
This affects common setups where the related entity has a `@DeleteDateColumn` (soft delete). Even with a non-nullable FK, soft-delete is not a data-integrity violation; it’s expected state, so dropping parent rows is a behavior regression for many users.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3968-3986]
- src/find-options/FindOptionsUtils.ts[206-216]
- src/query-builder/SelectQueryBuilder.ts[2157-2167]
- src/query-builder/SelectQueryBuilder.ts[2361-2418]
- docs/docs/guides/8-migration-v1.md[428-448]
## Suggested fix approach
- When choosing INNER vs LEFT join for `nullable:false` relations, also consider soft-delete behavior:
- If the destination metadata has `deleteDateColumn` and `withDeleted` is **false**, keep using `LEFT JOIN` (or otherwise preserve the old semantics).
- Alternatively, if the new filtering behavior is intended, explicitly document this in the migration guide as an additional breaking case and add a regression test covering a soft-deleted required relation.

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


3. Wrong INNER JOIN scope ☑ 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder switches to INNER JOIN purely based on relation.isNullable, even for relation
types that don't have a join column (e.g., OneToMany/ManyToMany/OneToOne inverse). If users set
nullable: false on those relations, queries can start filtering out parent rows when the relation
is empty, causing silent data loss.
Code

src/query-builder/SelectQueryBuilder.ts[R4155-4156]

+                            type: relation.isNullable ? "left" : "inner",
                  select: true,
Evidence
nullable is a generic RelationOptions flag accepted by decorators like OneToMany/ManyToMany, and
RelationMetadata.isNullable is derived directly from args.options.nullable. Those relation types
often have no join column on the current table (see isWithJoinColumn), so nullable:false does
not imply the related row must exist; however the new code will generate INNER JOINs and filter out
rows.

src/query-builder/SelectQueryBuilder.ts[4153-4157]
src/query-builder/SelectQueryBuilder.ts[4396-4404]
src/query-builder/SelectQueryBuilder.ts[4714-4722]
src/decorator/options/RelationOptions.ts[20-24]
src/decorator/relations/OneToMany.ts[14-18]
src/decorator/relations/ManyToMany.ts[14-17]
src/metadata/RelationMetadata.ts[327-328]
src/metadata/RelationMetadata.ts[197-200]

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` uses `relation.isNullable ? &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;left&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; : &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;inner&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;` for joins created by find-options relation handling. Since `nullable` is allowed on relation types without join columns (e.g., OneToMany/ManyToMany/OneToOne inverse), setting `nullable:false` on those can incorrectly produce INNER JOINs and filter out parent rows.
### Issue Context
Use INNER JOIN only when `relation.isWithJoinColumn` (or equivalently `relation.isManyToOne || (relation.isOneToOne &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; relation.isOneToOneOwner)`) and `relation.isNullable === false`.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4153-4167]
- src/query-builder/SelectQueryBuilder.ts[4264-4273]
- src/query-builder/SelectQueryBuilder.ts[4393-4404]
- src/query-builder/SelectQueryBuilder.ts[4711-4722]

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



Remediation recommended
4. Duplicated join-type logic ☑ 🐞 Bug ⚙ Maintainability
Description
The “INNER join iff non-nullable + owns join column + (no soft-delete or withDeleted)” rule is
implemented multiple times (including twice inside FindOptionsUtils) instead of being centralized.
This increases the risk that future changes/fixes update one path (e.g., QueryBuilder find options)
but not another (e.g., eager/tree relation joining), leading to inconsistent SQL generation.
Code

src/find-options/FindOptionsUtils.ts[R321-336]

+                if (
+                    !relation.isNullable &&
+                    relation.isWithJoinColumn &&
+                    (!relation.inverseEntityMetadata.deleteDateColumn ||
+                        qb.expressionMap.withDeleted)
+                ) {
+                    qb.innerJoin(
+                        alias + "." + relation.propertyPath,
+                        relationAlias,
+                    )
+                } else {
+                    qb.leftJoin(
+                        alias + "." + relation.propertyPath,
+                        relationAlias,
+                    )
+                }
Evidence
FindOptionsUtils contains two separate inline implementations of the same rule
(applyRelationsRecursively and joinEagerRelations). SelectQueryBuilder extracted the same policy
into getRelationJoinType(), but FindOptionsUtils does not reuse it, so the policy can drift across
call paths over time.

src/find-options/FindOptionsUtils.ts[206-219]
src/find-options/FindOptionsUtils.ts[295-337]
src/query-builder/SelectQueryBuilder.ts[3935-3958]

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 join-type decision policy (nullable + join-column ownership + soft-delete + withDeleted) is duplicated in multiple locations, including twice in `FindOptionsUtils`. This duplication risks future divergence where different loading paths generate different joins for the same relation configuration.
### Issue Context
`SelectQueryBuilder` already has `getRelationJoinType()`, but `FindOptionsUtils` re-implements the same condition inline for both `applyRelationsRecursively` and `joinEagerRelations`.
### Fix Focus Areas
- src/find-options/FindOptionsUtils.ts[206-219]
- src/find-options/FindOptionsUtils.ts[295-337]
- src/query-builder/SelectQueryBuilder.ts[3935-3958]
### Suggested approach
- Extract a shared helper (e.g., `getRelationJoinType(relation, withDeleted)` or `shouldUseInnerJoinForRelation(relation, withDeleted)`) in a common module.
- Use it from:
- `SelectQueryBuilder.getRelationJoinType()` (delegate to helper)
- `FindOptionsUtils.applyRelationsRecursively()`
- `FindOptionsUtils.joinEagerRelations()`
- Keep return type consistent (e.g., `&amp;amp;amp;amp;#x27;inner&amp;amp;amp;amp;#x27;|&amp;amp;amp;amp;#x27;left&amp;amp;amp;amp;#x27;`) and adapt to `FindOptionsUtils`’s uppercase `join.direction` needs where necessary.

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


5. nullable:false JOIN docs missing ☑ 📘 Rule violation ✓ Correctness
Description
This PR changes generated SQL to use INNER JOIN for relations marked nullable: false, which is a
user-visible behavior change. The existing relations docs describe nullable only as database
nullability and are not updated to mention the join-generation impact.
Code

src/query-builder/SelectQueryBuilder.ts[4155]

+                            type: relation.isNullable ? "left" : "inner",
Evidence
Compliance requires documentation updates for user-facing behavior changes. The PR explicitly
introduces conditional INNER JOIN generation based on relation.isNullable, while the relations
documentation still explains nullable only in terms of whether the relation column can be NULL,
without mentioning query join behavior.

Rule 2: Docs updated for user-facing changes
src/query-builder/SelectQueryBuilder.ts[4153-4156]
docs/docs/relations/1-relations.md[17-21]

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 PR introduces user-visible query generation behavior: relations marked `nullable: false` now use `INNER JOIN` instead of `LEFT JOIN`. Documentation for relation options currently describes `nullable` only as DB nullability and does not mention this join-generation effect.
## Issue Context
This behavior affects SQL produced by find-options/eager relation loading and can impact results (e.g., rows filtered out if the DB data violates the non-null expectation) and query plans. Users need to know that setting `nullable: false` can change joins to `INNER JOIN`.
## Fix Focus Areas
- docs/docs/relations/1-relations.md[13-25]
- docs/docs/relations/5-eager-and-lazy-relations.md[64-67]

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


6. Test join assertion weak ☑ 🐞 Bug ⛯ Reliability
Description
The new test only asserts that the SQL contains "INNER JOIN" and "LEFT JOIN" somewhere, which
doesn't prove that requiredAuthor is INNER-joined and author is LEFT-joined. Strengthening the
assertion would better prevent regressions and false positives.
Code

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[R261-266]

+                // nullable=false relation (requiredAuthor) should use INNER JOIN
+                expect(query).to.contain("INNER JOIN")
+
+                // nullable=true relation (author) should still use LEFT JOIN
+                expect(query).to.contain("LEFT JOIN")
+
Evidence
The test checks only for the presence of join keywords, not that they correspond to specific
relations; the query could include these tokens due to other joins while still joining the targeted
relations incorrectly.

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[256-266]

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 SQL assertion is too generic and may pass even if the wrong relation uses INNER vs LEFT joins.
### Issue Context
The join clauses should be validated against the target relation names (e.g., `requiredAuthor` / `requiredAuthorId` and `author` / `authorId`) or stable aliases produced by TypeORM.
### Fix Focus Areas
- test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[251-275]

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


Grey Divider Grey Divider

Qodo Logo

@alumni
alumni requested review from alumni, gioboa and pkuczynski March 9, 2026 21:38
@pkg-pr-new

pkg-pr-new Bot commented Mar 9, 2026 •

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

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

commit: c597ecd

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8967fa4

@coveralls

coveralls commented Mar 9, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.278% (-0.003%) from 73.281%
when pulling c597ecd on chunghyunleeme:feat/nullable-inner-join
into ff00a3c on typeorm:master.

@alumni alumni changed the title feat: use inner join for non-nullable relations feat!: use inner join for non-nullable relations Mar 10, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 9e3ffd1

@alumni alumni mentioned this pull request Mar 13, 2026
6 of 7 tasks
@pkuczynski pkuczynski changed the title feat!: use inner join for non-nullable relations perf: use inner join for non-nullable relations Mar 18, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 18, 2026
@pkuczynski pkuczynski changed the title perf: use inner join for non-nullable relations perf(relations): use inner join for non-nullable ManyToOne and OneToOne relations Mar 19, 2026
@pkuczynski

Copy link
Copy Markdown
Member

Thanks for the PR — the concept is solid. I've made a few amendments and pushed them to the branch:

1. Scoped INNER JOIN to join-column relations only

The original code used relation.isNullable on all relation types, but nullable: false only guarantees a related row exists for relations that own the join column (ManyToOne, owning OneToOne). For OneToMany, ManyToMany, and inverse OneToOne, using INNER JOIN could silently drop parent rows when the collection is empty.

Changed all 6 locations to: !relation.isNullable && relation.isWithJoinColumn ? "inner" : "left"

2. Strengthened test assertions

The original test only checked expect(query).to.contain("INNER JOIN") which doesn't verify which relation uses which join type. Now asserts against specific table and alias names:

expect(query).to.match(/INNER JOIN .?user.? .?post__requiredAuthor.?/)
expect(query).to.match(/LEFT JOIN .?user.? .?post__author.?/)

3. Added migration guide entry

Documented the behavior change under ## Relations → ### nullable: false now uses INNER JOIN with a "potentially breaking" warning about data integrity.

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

Copy link
Copy Markdown

Persistent review updated to latest commit d366eca

@pkuczynski

Copy link
Copy Markdown
Member

Follow-up to my previous review — pushed additional changes:

4. Soft-delete safety

If the target entity has a @DeleteDateColumn, TypeORM appends IS NULL to the join condition to filter soft-deleted rows. With INNER JOIN, this would silently drop parent rows when the related entity is soft-deleted — a behavior regression for common setups.

Fixed: when the target entity has @DeleteDateColumn and withDeleted is not set, the join falls back to LEFT JOIN even for nullable: false relations. Extracted a getRelationJoinType() helper in SelectQueryBuilder to centralize this logic.

5. Comprehensive join strategy test suite

Added test/functional/relations/join-strategy/ with dedicated entities covering all relation types. 26 tests organized by relation type (ManyToOne, OneToOne owner, OneToOne inverse, OneToMany, ManyToMany, soft-delete interaction) × access method (QueryBuilder, find methods).

Each test verifies behavior through result counts — two posts are created (one with all relations, one with only required ones), so LEFT JOIN and INNER JOIN produce observably different results. QueryBuilder tests additionally assert the SQL join type via regex.

6. Relations documentation updated

Updated docs/docs/relations/1-relations.md and docs/docs/relations/5-eager-and-lazy-relations.md to document that nullable: false on ManyToOne/owning OneToOne now uses INNER JOIN.

7. SonarQube fix

Flattened nested if/else in FindOptionsUtils.ts (S6660).

@pkuczynski pkuczynski changed the title perf(relations): use inner join for non-nullable ManyToOne and OneToOne relations perf(relations)!: use inner join for non-nullable ManyToOne and OneToOne relations Mar 19, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 2c729e9

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

Copy link
Copy Markdown

Persistent review updated to latest commit 448d941

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

Copy link
Copy Markdown

Persistent review updated to latest commit 1809cc6

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit c597ecd

@pkuczynski
pkuczynski merged commit 7038fa1 into typeorm:master Mar 20, 2026
43 checks passed
pkuczynski added a commit that referenced this pull request Mar 21, 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.

5 participants