Skip to content

fix: use subquery with join map one methods - #11943

Merged
gioboa merged 4 commits into
typeorm:masterfrom
gioboa:fix/map-as-entity
Jan 25, 2026
Merged

gioboa merged 4 commits into
typeorm:masterfrom
gioboa:fix/map-as-entity

Conversation

@gioboa

@gioboa gioboa commented Jan 25, 2026 •

Copy link
Copy Markdown
Collaborator

Finalising #10769
That PR is not editable by maintainers and the last alignment with master is missing.
I'm doing this missing step and cherry picking the original commit.

--- ORIGINAL #10769 DESCRIPTON ---

Description of change

On #9354 there was a patch to map subquery results to an entity when using the leftJoinAndMapOne and innerJoinAndMapOne methods through a new parameter: mapAsEntity.

This unfortunately does not quite work as expected because the subquery is ignored since the join logic detects that there is metadata and the logic will override the subquery in favor of generated queries via metadata.

This problem is described by @cjsauer on the following comment: #9354 (comment)

Fixes #5637

Pull-Request Checklist

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

Summary by CodeRabbit

  • Tests
    • Added new test cases to verify correct behavior when join subqueries with conditions do not find matching data, ensuring left joins map to null and inner joins return no entity.
  • Refactor
    • Improved and unified the internal handling of subqueries within join operations for more consistent and maintainable logic.

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

Copy link
Copy Markdown

User description

Finalising #10769

Description of change

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

PR Type

Bug fix, Tests


Description

  • Fix join mapping with subqueries by detecting and handling subquery patterns early

  • Move subquery detection logic before metadata check to support function and string subqueries

  • Pass subquery to alias creation for proper SQL generation in join operations

  • Add test cases for leftJoinAndMapOne and innerJoinAndMapOne with subquery conditions


Diagram Walkthrough

flowchart LR
  A["Join Method Called"] --> B["Detect Subquery Pattern"]
  B --> C["Check if Entity or Subquery"]
  C -->|Entity| D["Use Metadata"]
  C -->|Subquery| E["Build/Parse Subquery"]
  D --> F["Create Alias with Metadata"]
  E --> G["Create Alias with SubQuery"]
  F --> H["Generate SQL"]
  G --> H
Loading

File Walkthrough

Relevant files
Bug fix
SelectQueryBuilder.ts
Refactor subquery detection and alias creation logic         

src/query-builder/SelectQueryBuilder.ts

  • Moved subquery detection logic before metadata check to handle both
    entity and subquery cases
  • Added isSubQuery detection that checks for function type or string
    patterns starting with '(' and ending with ')'
  • Extract and process subquery (either from function callback or string)
    before alias creation
  • Pass subQuery parameter to createAlias() when creating join aliases
    for subqueries
  • Removed duplicate subquery handling code from the else branch
+20/-14 
Tests
query-builder-joins.test.ts
Add subquery join mapping test cases                                         

test/functional/query-builder/join/query-builder-joins.test.ts

  • Add test for leftJoinAndMapOne with subquery that filters out matching
    results
  • Verify that join data is not loaded when subquery conditions exclude
    the related entity
  • Add test for innerJoinAndMapOne with subquery that filters out
    matching results
  • Verify that entire result is null when inner join subquery conditions
    exclude the related entity
+70/-0   

@pkg-pr-new

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

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

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

commit: dcdc8a1

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to dcdc8a1

CategorySuggestion                                                                                                                                    Impact
General
Improve subquery string detection robustness

Improve the robustness of string-based subquery detection by trimming whitespace
from the input string before checking if it starts and ends with parentheses.

src/query-builder/SelectQueryBuilder.ts [2194-2199]

 const isEntity = this.connection.hasMetadata(entityOrProperty)
+const trimmedEntity = typeof entityOrProperty === "string" ? entityOrProperty.trim() : ""
 const isSubQuery =
     (!isEntity && typeof entityOrProperty === "function") ||
     (typeof entityOrProperty === "string" &&
-        entityOrProperty.startsWith("(") &&
-        entityOrProperty.endsWith(")"))
+        trimmedEntity.startsWith("(") &&
+        trimmedEntity.endsWith(")"))
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies a potential edge case where a string with leading/trailing whitespace could be misidentified as not being a subquery, and the proposed fix of trimming the string is a valid improvement.

Low
  • More

Previous suggestions

Suggestions up to commit 37919f2
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent parameter name conflicts

Avoid potential parameter name conflicts between the main query and subqueries
by merging parameters carefully instead of overwriting them.

src/query-builder/SelectQueryBuilder.ts [2201-2212]

 let subQuery: string = ""
 if (isSubQuery) {
     if (typeof entityOrProperty === "string") {
         subQuery = entityOrProperty
     } else {
         const subQueryBuilder: SelectQueryBuilder<any> = (
             entityOrProperty as any
         )((this as any as SelectQueryBuilder<any>).subQuery())
-        this.setParameters(subQueryBuilder.getParameters())
+        const subQueryParams = subQueryBuilder.getParameters()
+        // Merge parameters carefully to avoid conflicts
+        Object.keys(subQueryParams).forEach(key => {
+            if (!this.expressionMap.parameters[key]) {
+                this.setParameter(key, subQueryParams[key])
+            }
+        })
         subQuery = subQueryBuilder.getQuery()
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a potential for parameter name collisions between the main query and a subquery, which could lead to incorrect query execution.

Medium
Improve subquery detection validation

Improve the subquery detection logic by adding more specific validation to
prevent misclassifying strings as subqueries.

src/query-builder/SelectQueryBuilder.ts [2194-2199]

 const isEntity = this.connection.hasMetadata(entityOrProperty)
 const isSubQuery =
     (!isEntity && typeof entityOrProperty === "function") ||
     (typeof entityOrProperty === "string" &&
-        entityOrProperty.startsWith("(") &&
-        entityOrProperty.endsWith(")"))
+        entityOrProperty.trim().startsWith("(") &&
+        entityOrProperty.trim().endsWith(")") &&
+        entityOrProperty.trim().toLowerCase().includes("select"))
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies a potential weakness in subquery detection, but the proposed fix of checking for "select" is also not robust and could be bypassed or cause false positives.

Low
✅ Suggestions up to commit 3919cde
CategorySuggestion                                                                                                                                    Impact
High-level
✅ Refactor join subquery logic
Suggestion Impact:The commit partially implemented the suggestion by replacing deprecated substr() methods with modern startsWith() and endsWith() methods for string checking, which was shown in the "After" example. However, the full refactoring to extract logic into separate helper methods was not implemented.

code diff:

-                entityOrProperty.substr(0, 1) === "(" &&
-                entityOrProperty.substr(-1) === ")")
+                entityOrProperty.startsWith("(") &&
+                entityOrProperty.endsWith(")"))

The logic for detecting and building subqueries within the join method is
complex. This logic should be extracted into a separate helper method to improve
the join method's clarity and maintainability.

Examples:

src/query-builder/SelectQueryBuilder.ts [2194-2212]
        const isEntity = this.connection.hasMetadata(entityOrProperty)
        const isSubQuery =
            (!isEntity && typeof entityOrProperty === "function") ||
            (typeof entityOrProperty === "string" &&
                entityOrProperty.substr(0, 1) === "(" &&
                entityOrProperty.substr(-1) === ")")

        let subQuery: string = ""
        if (isSubQuery) {
            if (typeof entityOrProperty === "string") {

 ... (clipped 9 lines)

Solution Walkthrough:

Before:

protected join(...) {
    // ...
    const isEntity = this.connection.hasMetadata(entityOrProperty)
    const isSubQuery =
        (!isEntity && typeof entityOrProperty === "function") ||
        (typeof entityOrProperty === "string" &&
            entityOrProperty.substr(0, 1) === "(" &&
            entityOrProperty.substr(-1) === ")")

    let subQuery: string = ""
    if (isSubQuery) {
        if (typeof entityOrProperty === "string") {
            subQuery = entityOrProperty
        } else {
            // ... build subquery from function
        }
    }
    // ...
}

After:

protected join(...) {
    // ...
    const isSubQuery = this.isSubQuery(entityOrProperty);
    let subQuery: string = "";
    if (isSubQuery) {
        subQuery = this.buildSubQuery(entityOrProperty);
    }
    // ...
}

private isSubQuery(target: any): boolean {
    const isEntity = this.connection.hasMetadata(target);
    return (!isEntity && typeof target === "function") ||
        (typeof target === "string" &&
            target.startsWith("(") &&
            target.endsWith(")"));
}

private buildSubQuery(target: any): string {
    // ... logic to build subquery string from function or return the string directly
}
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies complex logic for subquery detection in the join method and proposes a valid refactoring to improve clarity and maintainability, which is valuable for such a core method.

Low

@gioboa gioboa changed the title Fix/map as entity fix: use subquery with join map one methods Jan 25, 2026
@gioboa gioboa mentioned this pull request Jan 25, 2026
7 tasks done
@gioboa
gioboa requested review from G0maa, alumni and naorpeled January 25, 2026 12:56
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review


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

Grey Divider

Previous review results

Review updated until commit dcdc8a1

Results up to commit 37919f2


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

Grey Divider
Remediation recommended
1. Missing docs for subquery with leftJoinAndMapOne 📘 Rule violation ✧ Quality
Description
• The PR fixes a bug where subqueries were ignored when using leftJoinAndMapOne and
  innerJoinAndMapOne with the mapAsEntity parameter (issue #5637)
• The documentation in docs/docs/query-builder/1-select-query-builder.md shows basic usage of
  leftJoinAndMapOne but does not document the subquery usage pattern with the mapAsEntity
  parameter
• Users need documentation showing how to use subqueries with these methods, especially since this
  was a previously broken feature that is now fixed
Code

src/query-builder/SelectQueryBuilder.ts[R2194-2212]

+        const isEntity = this.connection.hasMetadata(entityOrProperty)
+        const isSubQuery =
+            (!isEntity && typeof entityOrProperty === "function") ||
+            (typeof entityOrProperty === "string" &&
+                entityOrProperty.startsWith("(") &&
+                entityOrProperty.endsWith(")"))
+
+        let subQuery: string = ""
+        if (isSubQuery) {
+            if (typeof entityOrProperty === "string") {
+                subQuery = entityOrProperty
+            } else {
+                const subQueryBuilder: SelectQueryBuilder<any> = (
+                    entityOrProperty as any
+                )((this as any as SelectQueryBuilder<any>).subQuery())
+                this.setParameters(subQueryBuilder.getParameters())
+                subQuery = subQueryBuilder.getQuery()
+            }
+        }
Evidence
The compliance rule requires documentation updates for user-facing changes. The PR description
states this fixes issue #5637 where subqueries with leftJoinAndMapOne/innerJoinAndMapOne were
not working. The tests show the new usage pattern with subqueries (lines 574-607, 1060-1093), but
the documentation at docs/docs/query-builder/1-select-query-builder.md only shows basic usage
without subqueries. The code changes enable a previously broken feature, making it a user-facing
change that requires documentation.

Rule 2: Docs updated for user-facing changes
test/functional/query-builder/join/query-builder-joins.test.ts[588-601]

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 documentation needs to be updated to show users how to use subqueries with `leftJoinAndMapOne` and `innerJoinAndMapOne` methods, particularly with the `mapAsEntity` parameter. This feature was previously broken (issue #5637) and is now fixed.

## Issue Context
The PR fixes a bug where subqueries were ignored when using these join methods with entities. The tests demonstrate the correct usage pattern, but users need documentation to discover and use this feature.

## Fix Focus Areas
- docs/docs/query-builder/1-select-query-builder.md[753-779]

Add a new subsection after line 778 showing:
1. How to use a subquery function with leftJoinAndMapOne
2. How to pass the entity class as the last parameter (mapAsEntity)
3. An example similar to the test cases showing filtering within the subquery

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


2. hasMetadata Called with Invalid Function Type 🐞 Bug ✓ Correctness
Description
• The code calls this.connection.hasMetadata(entityOrProperty) at line 2194 before checking if
  entityOrProperty is a subquery builder function
• When entityOrProperty is a function like (qb) => qb.subQuery().from(Tag, 'tag'), this
  arbitrary function is passed to hasMetadata() which expects an EntityTarget (entity class
  constructor, EntitySchema, string, or object)
• The findMetadata() implementation uses Map.get() with the function as key, which will fail to
  find metadata for non-entity functions, but this premature call is semantically incorrect and could
  cause issues if the Map lookup has side effects
Code

src/query-builder/SelectQueryBuilder.ts[R2194-2199]

+        const isEntity = this.connection.hasMetadata(entityOrProperty)
+        const isSubQuery =
+            (!isEntity && typeof entityOrProperty === "function") ||
+            (typeof entityOrProperty === "string" &&
+                entityOrProperty.startsWith("(") &&
+                entityOrProperty.endsWith(")"))
Evidence
The old code (removed lines 2224-2236) checked typeof entityOrProperty === 'function' first before
any metadata operations. The new code reverses this order, calling hasMetadata() unconditionally.
The findMetadata() method in DataSource.ts (lines 682-720) performs a Map.get() lookup and
iterates through metadata, which is unnecessary work for subquery functions. While the logic still
works (hasMetadata returns false, then isSubQuery becomes true via !isEntity check), calling
hasMetadata with invalid input violates the method's contract and could cause issues if the
implementation changes.

src/query-builder/SelectQueryBuilder.ts[2194-2199]
src/data-source/DataSource.ts[682-686]
src/common/EntityTarget.ts[7-11]

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 code calls `hasMetadata()` with `entityOrProperty` before validating whether it&#x27;s a subquery builder function. This passes invalid input to a method expecting EntityTarget types.

## Issue Context
When users call join methods with subquery builders like `(qb) =&gt; qb.subQuery().from(Tag, &#x27;tag&#x27;)`, this function is passed to `hasMetadata()` which expects entity classes, EntitySchemas, strings, or specific objects. While the code still works, it violates the method contract and performs unnecessary work.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2194-2199]: Reorder the checks to validate function type before calling hasMetadata

The fix should check `typeof entityOrProperty === &#x27;function&#x27;` first, then only call `hasMetadata()` for non-function values to avoid passing subquery builder functions to the metadata system.

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


Results up to commit 3919cde


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

Grey Divider
Action required
1. Subquery incorrectly treated as entity join 🐞 Bug ✓ Correctness
Description
• When using leftJoinAndMapOne/innerJoinAndMapOne with a subquery function AND a mapAsEntity
  parameter that has metadata (e.g., Tag entity), the join incorrectly takes the entity join path (if
  block at line 2215) instead of the subquery path (else block at line 2242)
• This occurs because joinAttribute.metadata getter (JoinAttribute.ts line 210-211) returns metadata
  from mapAsEntity when entityOrProperty is a subquery function, making joinAttributeMetadata truthy
• The entity join path doesn't properly handle subqueries - it may generate incorrect SQL by
  treating the subquery as an entity table
• The new test cases at lines 574-607 and 1060-1093 use this exact pattern (subquery function with
  Tag as mapAsEntity), demonstrating the affected scenario
Code

src/query-builder/SelectQueryBuilder.ts[R2194-2212]

+        const isEntity = this.connection.hasMetadata(entityOrProperty)
+        const isSubQuery =
+            (!isEntity && typeof entityOrProperty === "function") ||
+            (typeof entityOrProperty === "string" &&
+                entityOrProperty.substr(0, 1) === "(" &&
+                entityOrProperty.substr(-1) === ")")
+
+        let subQuery: string = ""
+        if (isSubQuery) {
+            if (typeof entityOrProperty === "string") {
+                subQuery = entityOrProperty
+            } else {
+                const subQueryBuilder: SelectQueryBuilder<any> = (
+                    entityOrProperty as any
+                )((this as any as SelectQueryBuilder<any>).subQuery())
+                this.setParameters(subQueryBuilder.getParameters())
+                subQuery = subQueryBuilder.getQuery()
+            }
+        }
Evidence
The bug occurs when entityOrProperty is a subquery function and mapAsEntity has metadata. The
isSubQuery check correctly identifies it as a subquery (line 2196: !isEntity && typeof
entityOrProperty === 'function'), and the subquery is executed (lines 2202-2212). However,
joinAttribute.metadata getter returns metadata from mapAsEntity (JoinAttribute.ts lines 210-211),
making joinAttributeMetadata truthy. This causes the code to take the entity join path (line 2215 if
block) which passes the subQuery to createAlias but is designed for entity joins, not subquery
joins. The old code avoided this by only executing subquery logic in the else block where metadata
was guaranteed to be falsy.

src/query-builder/SelectQueryBuilder.ts[2194-2231]
src/query-builder/JoinAttribute.ts[209-212]
test/functional/query-builder/join/query-builder-joins.test.ts[588-601]

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 a subquery join uses mapAsEntity parameter with an entity that has metadata, the code incorrectly takes the entity join path instead of the subquery path. This happens because joinAttribute.metadata returns the mapAsEntity metadata even when entityOrProperty is a subquery function.

## Issue Context
The refactoring moved subquery detection and execution before the joinAttributeMetadata check. While the subquery is correctly detected and executed, the subsequent if/else branching on joinAttributeMetadata doesn&#x27;t account for the case where a subquery has mapAsEntity metadata.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2214-2252]

Change the branching logic to check isSubQuery first, ensuring subquery joins always use the else block (subquery path) regardless of whether mapAsEntity has metadata. The if block should only handle true entity joins where entityOrProperty itself is an entity or relation.

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


Qodo Logo

Comment thread src/query-builder/SelectQueryBuilder.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 37919f2

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

Copy link
Copy Markdown

Persistent review updated to latest commit dcdc8a1

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 81.12% (+0.03%) from 81.095%
when pulling dcdc8a1 on gioboa:fix/map-as-entity
into 5237bee on typeorm:master.

@gioboa
gioboa merged commit 710d176 into typeorm:master Jan 25, 2026
38 checks passed
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

leftJoinAndMapOne does not add target property to entity

7 participants