You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: use subquery with join map one methods - #11943
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.
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 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.
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
Improve the robustness of string-based subquery detection by trimming whitespace from the input string before checking if it starts and ends with parentheses.
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.
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.
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.
✅ Refactor join subquery logicSuggestion 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.
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.
protectedjoin(...){// ...const isSubQuery =this.isSubQuery(entityOrProperty);letsubQuery: string="";if(isSubQuery){subQuery=this.buildSubQuery(entityOrProperty);}// ...}privateisSubQuery(target: any): boolean {constisEntity=this.connection.hasMetadata(target);return(!isEntity&&typeoftarget==="function")||(typeoftarget==="string"&&target.startsWith("(")&&target.endsWith(")"));}privatebuildSubQuery(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
changed the title
Fix/map as entity
fix: use subquery with join map one methods
Jan 25, 2026
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
+ 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.
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
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.
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'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) => qb.subQuery().from(Tag, 'tag')`, 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 === 'function'` 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
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
+ 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.
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'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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
leftJoinAndMapOneandinnerJoinAndMapOnemethods 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
masterbranchnpm run formatto apply prettier formattingnpm run testpasses with this changeFixes #0000Summary by CodeRabbit