Skip to content

fix(query-builder): wrap inner joins under left joins correctly - #11137

Merged
alumni merged 28 commits into
typeorm:masterfrom
harm-less:fix/left-and-inner-join
Jun 18, 2026
Merged

alumni merged 28 commits into
typeorm:masterfrom
harm-less:fix/left-and-inner-join

Conversation

@harm-less

@harm-less harm-less commented Nov 18, 2024 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #3080. After 6 years of knowing this issue exists, it's finally no more!

This StackOverflow still explain the case fairly well. Simply put, if the nested INNER JOIN returns 0 rows, the entire query will by definition return 0 results even if the FROM table or the LEFT JOIN had results. So the ON condition of the parent LEFT JOIN wraps the INNER JOIN in order to prevent this from happening.

We are running this on a Postgres DB.

This is what the PR will do to queries. I took an advanced example from our application.

Before (current TypeORM version):

inner join "public"."publication_links" "pubLink" on
    "pubLink"."id" = "variant"."publicationId"
    and ("pubLink"."deletedAt" is null)
inner join "public"."merchants" "merchant" on
    "merchant"."id" = "pubLink"."retailerId"
    and ("merchant"."deletedAt" is null)
inner join "public"."merchant_channels" "merchantChannel" on
    "merchantChannel"."retailerId" = "merchant"."id"
    and ("merchantChannel"."isActive" = $1)
inner join "public"."channel_data" "channelData" on
    "channelData"."id" = "merchantChannel"."channelId"
    and (("channelData"."slug" = $2)
        and "channelData"."deletedAt" is null)
left join "public"."affiliate_metadata" "affiliateMeta" on
    "affiliateMeta"."retailerId" = "merchant"."id"
    and ("affiliateMeta"."affiliateId" = $3)
left join "public"."ab_test_variants" "abTestVariant" on
    "abTestVariant"."publicationVariantsId" = "variant"."id"
left join "public"."ab_tests" "abTest" on
    "abTest"."id" = "abTestVariant"."publicationAbTestsId"
    and ("abTest"."deletedAt" is null)
left join "public"."ab_test_channels" "abTestChannel" on
    "abTestChannel"."publicationAbTestsId" = "abTest"."id"
left join "public"."channel_references" "channelRef" on
    "channelRef"."id" = "abTestChannel"."channelsId"
    and (("channelRef"."slug" = $4)
        and "channelRef"."deletedAt" is null)
left join "public"."variant_channels" "variantChannel" on
    "variantChannel"."publicationVariantId" = "variant"."id"
    and ("variantChannel"."isActive" = $5)
inner join "public"."channel_mappings" "channelMap" on
    "channelMap"."id" = "variantChannel"."channelId"
    and (("channelMap"."slug" = $6)
        and "channelMap"."deletedAt" is null)
left join "public"."variant_meta" "variantMeta" on
    "variantMeta"."publicationVariantId" = "variant"."id"
    and ("variantMeta"."affiliateId" = $7)
left join "public"."variant_meta_categories" "variantMetaCategory" on
    "variantMetaCategory"."affiliateCmsPublicationVariantsMetaId" = "variantMeta"."id"
left join "public"."cms_categories" "cmsCategory" on
    "cmsCategory"."id" = "variantMetaCategory"."affiliateCmsCategoriesId"
    and ("cmsCategory"."affiliateId" = $8
        and "cmsCategory"."deletedAt" is null)
left join "public"."variant_meta_themes" "variantMetaTheme" on
    "variantMetaTheme"."affiliateCmsPublicationVariantsMetaId" = "variantMeta"."id"
left join "public"."cms_themes" "cmsTheme" on
    "cmsTheme"."id" = "variantMetaTheme"."affiliateCmsThemesId"
    and ("cmsTheme"."affiliateId" = $9)
left join "public"."top_positions" "topPosition" on
    "topPosition"."publicationVariantId" = "variant"."id"
    and ("topPosition"."affiliateId" = $10
        and "topPosition"."themeId" is null
        and ("topPosition"."until" is null
            or "topPosition"."until" > $11)
        and "topPosition"."deletedAt" is null)

After (this PR):

inner join "public"."publication_links" "pubLink"
inner join "public"."merchants" "merchant"
inner join "public"."merchant_channels" "merchantChannel"
inner join "public"."channel_data" "channelData" on
    "channelData"."id" = "merchantChannel"."channelId"
    and ("channelData"."id" in ($1)
        and "channelData"."deletedAt" is null) on
    "merchantChannel"."retailerId" = "merchant"."id"
    and ("merchantChannel"."isActive" = $2)
left join "public"."affiliate_metadata" "affiliateMeta" on
    "affiliateMeta"."retailerId" = "merchant"."id"
    and ("affiliateMeta"."affiliateId" = $3) on
    "merchant"."id" = "pubLink"."retailerId"
    and ("merchant"."deletedAt" is null) on
    "pubLink"."id" = "variant"."publicationId"
    and ("pubLink"."deletedAt" is null)
left join "public"."ab_test_variants" "abTestVariant" on
    "abTestVariant"."publicationVariantsId" = "variant"."id"
left join "public"."ab_tests" "abTest"
left join "public"."ab_test_channels" "abTestChannel" on
    "abTestChannel"."publicationAbTestsId" = "abTest"."id"
left join "public"."channel_references" "channelRef" on
    "channelRef"."id" = "abTestChannel"."channelsId"
    and ("channelRef"."id" in ($4)
        and "channelRef"."deletedAt" is null) on
    "abTest"."id" = "abTestVariant"."publicationAbTestsId"
    and ("abTest"."deletedAt" is null)
inner join "public"."variant_channels" "variantChannel"
inner join "public"."channel_mappings" "channelMap" on
    "channelMap"."id" = "variantChannel"."channelId"
    and ("channelMap"."id" in ($5)
        and "channelMap"."deletedAt" is null) on
    "variantChannel"."publicationVariantId" = "variant"."id"
    and ("variantChannel"."isActive" = $6)
left join "public"."variant_meta" "variantMeta"
left join "public"."variant_meta_categories" "variantMetaCategory" on
    "variantMetaCategory"."affiliateCmsPublicationVariantsMetaId" = "variantMeta"."id"
left join "public"."cms_categories" "cmsCategory" on
    "cmsCategory"."id" = "variantMetaCategory"."affiliateCmsCategoriesId"
    and ("cmsCategory"."affiliateId" = $7
        and "cmsCategory"."deletedAt" is null)
left join "public"."variant_meta_themes" "variantMetaTheme" on
    "variantMetaTheme"."affiliateCmsPublicationVariantsMetaId" = "variantMeta"."id"
left join "public"."cms_themes" "cmsTheme" on
    "cmsTheme"."id" = "variantMetaTheme"."affiliateCmsThemesId"
    and ("cmsTheme"."affiliateId" = $8) on
    "variantMeta"."publicationVariantId" = "variant"."id"
    and ("variantMeta"."affiliateId" = $9)
left join "public"."top_positions" "topPosition" on
    "topPosition"."publicationVariantId" = "variant"."id"
    and ("topPosition"."affiliateId" = $10
        and "topPosition"."themeId" is null
        and ("topPosition"."until" is null
            or "topPosition"."until" > $11)
        and "topPosition"."deletedAt" is null)

I'll be runnning this code on our production environment soon. So I should have a better overview of this change in the coming days/weeks in case more info is needed.

Pull-Request Checklist

  • Yes to all

@harm-less harm-less changed the title Fixes inner joining wrapping left joined tables Fixes inner join wrapping left joined tables Nov 18, 2024
@@ -295,6 +295,51 @@ describe("query builder > joins", () => {
}),
))

it("should load results from a left join with a child inner join both of which have zero results", () =>

@harm-less harm-less Nov 18, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both these tests will fail on the current TypeORM version

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can I ask you to solve the conflicts please?

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 9c15b7a

CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Fix parent-child join relationship mapping
Suggestion Impact:The commit removed the `|| "parentless"` parent-alias fallback and changed parent lookup to only occur when `joinAttribute.parentAlias` is present, allowing joins with no parent to be treated as roots and preventing child joins from being incorrectly grouped under a synthetic "parentless" key.

code diff:

@@ -2428,10 +2366,11 @@
             mappedTrees: Record<string, JoinAttributeTree> // flattened lookup join attribute table
         }>(
             ({ trees, mappedTrees }, joinAttribute) => {
-                const parentAlias = joinAttribute.parentAlias || "parentless"
                 const destinationTableAlias = joinAttribute.alias.name
 
-                const existingTree = mappedTrees[parentAlias]
+                const existingTree = joinAttribute.parentAlias
+                    ? mappedTrees[joinAttribute.parentAlias]
+                    : undefined
                 const joinAttributeTree: JoinAttributeTree = {
                     children: [],
                     joinAttribute,
@@ -2450,13 +2389,13 @@

Fix the join-tree building logic to correctly handle root-level joins and their
children. The current implementation fails to find the parent for a child join
if the parent join itself has no parent, breaking the nesting.

src/query-builder/SelectQueryBuilder.ts [2426-2450]

 const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
     trees: Array<JoinAttributeTree>
     mappedTrees: Record<string, JoinAttributeTree>
 }>(
     ({ trees, mappedTrees }, joinAttribute) => {
-        const parentAlias = joinAttribute.parentAlias || "parentless"
         const destinationTableAlias = joinAttribute.alias.name
+        const parentAlias = joinAttribute.parentAlias
 
-        const existingTree = mappedTrees[parentAlias]
         const joinAttributeTree: JoinAttributeTree = {
             children: [],
             joinAttribute,
         }
-        if (existingTree) {
-            existingTree.children.push(joinAttributeTree)
+        
+        if (parentAlias) {
+            const existingTree = mappedTrees[parentAlias]
+            if (existingTree) {
+                existingTree.children.push(joinAttributeTree)
+            } else {
+                trees.push(joinAttributeTree)
+            }
         } else {
             trees.push(joinAttributeTree)
         }
 
         mappedTrees[destinationTableAlias] = joinAttributeTree
 
         return { trees, mappedTrees }
     },
     { trees: [], mappedTrees: {} },
 )

[Suggestion processed]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical flaw in the join-tree building logic where a root join's parent is not correctly identified, leading to incorrect nesting of subsequent child joins.

High
  • Update

Previous suggestions

Suggestions up to commit f0bb366
CategorySuggestion                                                                                                                                    Impact
Possible issue
Conditional parentheses wrapping for joins

Refine the join logic to wrap nested joins in parentheses only when a LEFT JOIN
has an INNER JOIN child, as this is the primary case requiring it. This avoids
unnecessary parentheses for other join combinations.

src/query-builder/SelectQueryBuilder.ts [2375-2380]

-const resolvedChildJoinAttributesPrefix = resolvedChildJoinAttributes
+const shouldWrapInParentheses = resolvedChildJoinAttributes && 
+    joinAttr.direction === "LEFT" && 
+    children.some(child => child.joinAttribute.direction === "INNER")
+const resolvedChildJoinAttributesPrefix = shouldWrapInParentheses
     ? "( "
     : ""
-const resolvedChildJoinAttributesPostfix = resolvedChildJoinAttributes
+const resolvedChildJoinAttributesPostfix = shouldWrapInParentheses
     ? " )"
     : ""
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that parentheses are only strictly necessary for LEFT JOIN with nested INNER JOINs. While the current implementation is not incorrect, applying parentheses more selectively improves SQL query readability and avoids potential issues with database optimizers or non-standard SQL dialects.

Medium
Suggestions up to commit 77978eb
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle out-of-order join dependencies

Refactor the join tree building logic to correctly handle out-of-order join
dependencies by introducing a mechanism to manage and process "orphan" joins.

src/query-builder/SelectQueryBuilder.ts [2324-2348]

 const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
     trees: Array<JoinAttributeTree>
     mappedTrees: Record<string, JoinAttributeTree>
+    orphans: Array<JoinAttributeTree>
 }>(
-    ({ trees, mappedTrees }, joinAttribute) => {
-        const parentAlias = joinAttribute.parentAlias || "parentless"
+    ({ trees, mappedTrees, orphans }, joinAttribute) => {
+        const parentAlias = joinAttribute.parentAlias
         const destinationTableAlias = joinAttribute.alias.name
 
-        const existingTree = mappedTrees[parentAlias]
         const joinAttributeTree: JoinAttributeTree = {
             children: [],
             joinAttribute,
         }
-        if (existingTree) {
-            existingTree.children.push(joinAttributeTree)
+
+        if (parentAlias) {
+            const existingTree = mappedTrees[parentAlias]
+            if (existingTree) {
+                existingTree.children.push(joinAttributeTree)
+            } else {
+                orphans.push(joinAttributeTree)
+            }
         } else {
             trees.push(joinAttributeTree)
         }
 
         mappedTrees[destinationTableAlias] = joinAttributeTree
 
-        return { trees, mappedTrees }
+        // Process orphans that can now find their parent
+        const remainingOrphans = orphans.filter(orphan => {
+            const parent = mappedTrees[orphan.joinAttribute.parentAlias!]
+            if (parent) {
+                parent.children.push(orphan)
+                return false
+            }
+            return true
+        })
+
+        return { trees, mappedTrees, orphans: remainingOrphans }
     },
-    { trees: [], mappedTrees: {} },
+    { trees: [], mappedTrees: {}, orphans: [] },
 )
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical flaw in the join tree construction logic. The current implementation fails if join attributes are not ordered by dependency, leading to an incorrect join hierarchy and malformed SQL. The proposed fix robustly handles out-of-order joins by temporarily storing and re-processing "orphan" joins, which is a critical improvement for query correctness.

High
✅ Suggestions up to commit 089a6fb
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Handle out-of-order join dependencies correctly
Suggestion Impact:The commit partially adjusted the join tree reducer in the suggested area by removing the `"parentless"` fallback and making parent alias lookup conditional on `joinAttribute.parentAlias`, but it did not introduce an `orphans` map or otherwise handle out-of-order join dependencies as proposed.

code diff:

@@ -2326,10 +2366,11 @@
             mappedTrees: Record<string, JoinAttributeTree> // flattened lookup join attribute table
         }>(
             ({ trees, mappedTrees }, joinAttribute) => {
-                const parentAlias = joinAttribute.parentAlias || "parentless"
                 const destinationTableAlias = joinAttribute.alias.name
 
-                const existingTree = mappedTrees[parentAlias]
+                const existingTree = joinAttribute.parentAlias
+                    ? mappedTrees[joinAttribute.parentAlias]
+                    : undefined
                 const joinAttributeTree: JoinAttributeTree = {
                     children: [],
                     joinAttribute,
@@ -2348,13 +2389,13 @@

Refactor the join attribute tree-building logic to correctly handle out-of-order
join dependencies by introducing an orphans map. This ensures joins are
correctly nested even when their parent join is defined later in the query.

src/query-builder/SelectQueryBuilder.ts [2324-2348]

 const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
     trees: Array<JoinAttributeTree>
     mappedTrees: Record<string, JoinAttributeTree>
+    orphans: Record<string, Array<JoinAttributeTree>>
 }>(
-    ({ trees, mappedTrees }, joinAttribute) => {
-        const parentAlias = joinAttribute.parentAlias || "parentless"
+    ({ trees, mappedTrees, orphans }, joinAttribute) => {
+        const parentAlias = joinAttribute.parentAlias
         const destinationTableAlias = joinAttribute.alias.name
 
-        const existingTree = mappedTrees[parentAlias]
         const joinAttributeTree: JoinAttributeTree = {
-            children: [],
+            children: orphans[destinationTableAlias] || [],
             joinAttribute,
         }
-        if (existingTree) {
-            existingTree.children.push(joinAttributeTree)
+
+        if (parentAlias && mappedTrees[parentAlias]) {
+            mappedTrees[parentAlias].children.push(joinAttributeTree)
+        } else if (parentAlias) {
+            if (!orphans[parentAlias]) orphans[parentAlias] = []
+            orphans[parentAlias].push(joinAttributeTree)
         } else {
             trees.push(joinAttributeTree)
         }
 
         mappedTrees[destinationTableAlias] = joinAttributeTree
+        delete orphans[destinationTableAlias]
 
-        return { trees, mappedTrees }
+        return { trees, mappedTrees, orphans }
     },
-    { trees: [], mappedTrees: {} },
+    { trees: [], mappedTrees: {}, orphans: {} },
 )
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical flaw where out-of-order join definitions would break the new tree-building logic, leading to incorrectly generated SQL. The proposed fix using an orphans map is a robust solution to this problem.

High

@pkg-pr-new

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

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

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

commit: 41260e4

@harm-less

harm-less commented Jan 5, 2026 •

Copy link
Copy Markdown
Contributor Author

@gioboa Done! Test are running and seemingly as expected 👍

As I mentioned in the bottom of the description, we've been running this fix in our production environment for the past year without issue. In fact, it ran as expected and we couldn't even update to the latest TypeORM without this fix. So assuming this is merged we finally can 👌
So I'm glad to see movement!

Btw, I think the suggestion from Qodo is not necessary as the query builder doesn't allow for out of order joins, correct?

@coveralls

coveralls commented Jan 5, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.265% (+0.02%) from 73.246%
when pulling bd9ce92 on harm-less:fix/left-and-inner-join
into e2284d8 on typeorm:master.

@gioboa gioboa changed the title Fixes inner join wrapping left joined tables fix: fix up inner join wrapping left joined tables Jan 17, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

🐞 Bugs (3) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Action Required

1. Multiple Root Joins Incorrectly Nested 🐞 Bug
Description
• When multiple joins have no parent alias (root-level joins), they are incorrectly nested as
  children of the first root join instead of being treated as independent siblings
• This occurs because all joins without a parentAlias are assigned the same key 'parentless',
  causing the second and subsequent root joins to be added as children of the first
• Results in incorrect SQL structure where independent joins are wrapped inside each other,
  producing wrong query results or failures

correctness

Code

src/query-builder/SelectQueryBuilder.ts[R2329-2341]

+                const parentAlias = joinAttribute.parentAlias || "parentless"
+                const destinationTableAlias = joinAttribute.alias.name
+
+                const existingTree = mappedTrees[parentAlias]
+                const joinAttributeTree: JoinAttributeTree = {
+                    children: [],
+                    joinAttribute,
+                }
+                if (existingTree) {
+                    existingTree.children.push(joinAttributeTree)
+                } else {
+                    trees.push(joinAttributeTree)
+                }
Evidence
The reduce function assigns 'parentless' to all joins without a parentAlias. When processing the
first root join, mappedTrees['parentless'] is undefined, so it's added to the trees array. When
processing the second root join, mappedTrees['parentless'] now exists (pointing to the first root
join), so the second join is incorrectly added as a child via
existingTree.children.push(joinAttributeTree). This creates a nested structure instead of sibling
root joins.

src/query-builder/SelectQueryBuilder.ts[2329-2341]

Agent Prompt
## Issue Description
The join tree construction incorrectly nests multiple root-level joins (joins without a parent alias) as children of the first root join, instead of treating them as independent sibling joins.

## Issue Context
In the reduce function that builds the join tree structure, all joins without a parentAlias are assigned the string &#x27;parentless&#x27;. This causes:
1. First root join: Creates mappedTrees[&#x27;parentless&#x27;] and is added to trees array
2. Second root join: Finds mappedTrees[&#x27;parentless&#x27;] exists, incorrectly adds itself as a child
3. Result: Nested structure instead of sibling root joins

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2328-2345]

Change the logic so that:
1. Joins without a parentAlias should always be added to the trees array (not as children)
2. Only joins with an actual parentAlias should be added as children to their parent
3. Remove the &#x27;parentless&#x27; fallback or use it only for lookup purposes, not for parent-child relationships

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


2. Invalid SQL for Multiple Sibling Joins 🐞 Bug
Description
• When a join has multiple children (e.g., post.categories and post.tags), all child joins are
  concatenated and wrapped in a single pair of parentheses
• This produces invalid SQL syntax like 'LEFT JOIN ( table1 alias1 LEFT JOIN child1 ON ... LEFT JOIN
  child2 ON ... ) ON ...'
• Parenthesized join syntax in SQL does not support multiple sibling joins within one parenthesis
  group, causing query execution failures

correctness

Code

src/query-builder/SelectQueryBuilder.ts[R2369-2380]

+        const resolvedChildJoinAttributes = (children || [])
+            .map((joinTreeChild) => {
+                return this.createJoinTreeRecursivly(joinTreeChild)
+            })
+            .join(" ")
+
+        const resolvedChildJoinAttributesPrefix = resolvedChildJoinAttributes
+            ? "( "
+            : ""
+        const resolvedChildJoinAttributesPostfix = resolvedChildJoinAttributes
+            ? " )"
+            : ""
Evidence
The code concatenates all child joins with .join(' ') and wraps them in a single pair of
parentheses. When a parent has multiple children, this creates invalid SQL because parenthesized
joins only support a single nested join path, not multiple sibling joins in one group. For example,
if 'post' has joins to both 'categories' and 'tags', the generated SQL would attempt to nest both
inside one parenthesis pair, which is syntactically invalid.

src/query-builder/SelectQueryBuilder.ts[2369-2380]

Agent Prompt
## Issue Description
When a join has multiple children (sibling joins), they are all concatenated and wrapped in a single pair of parentheses, producing invalid SQL syntax that fails to execute.

## Issue Context
The recursive join generation concatenates all child joins with spaces and wraps them in one parenthesis pair. SQL parenthesized join syntax only supports a single nested join path, not multiple sibling joins within one group.

Example problematic SQL:
```sql
LEFT JOIN ( table1 alias1 LEFT JOIN child1 ON ... LEFT JOIN child2 ON ... ) ON ...
```

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2369-2380]
- src/query-builder/SelectQueryBuilder.ts[2388-2402]
- src/query-builder/SelectQueryBuilder.ts[2424-2437]
- src/query-builder/SelectQueryBuilder.ts[2477-2490]

Consider one of these approaches:
1. Only apply parentheses to the first child, keep others as flat joins
2. Wrap each child join separately in its own parentheses
3. Flatten sibling joins to avoid parentheses when multiple children exist
4. Restructure the tree to only support single-path nesting

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


3. Parenthesized Joins Unsupported on Some Databases 🐞 Bug
Description
• The new implementation generates parenthesized join syntax (e.g., 'LEFT JOIN ( table1 LEFT JOIN
  table2 ON ... ) ON ...') for nested joins
• This syntax is not supported by all databases: Oracle, SQL Server, and MySQL versions prior to
  8.0.31 do not support parenthesized joins
• Queries with nested joins will fail on these database engines with SQL syntax errors, breaking
  existing functionality

reliability

Code

src/query-builder/SelectQueryBuilder.ts[R2375-2397]

+        const resolvedChildJoinAttributesPrefix = resolvedChildJoinAttributes
+            ? "( "
+            : ""
+        const resolvedChildJoinAttributesPostfix = resolvedChildJoinAttributes
+            ? " )"
+            : ""
+
+        // if join was build without relation (e.g. without "post.category") then it means that we have direct
+        // table to join, without junction table involved. This means we simply join direct table.
+        if (!parentAlias || !relation) {
+            const destinationJoin = joinAttr.alias.subQuery
+                ? joinAttr.alias.subQuery
+                : this.getTableName(destinationTableName)
+            return (
+                " " +
+                joinAttr.direction +
+                " JOIN " +
+                resolvedChildJoinAttributesPrefix +
+                destinationJoin +
+                " " +
+                this.escape(destinationTableAlias) +
+                resolvedChildJoinAttributes +
+                resolvedChildJoinAttributesPostfix +
Evidence
The code adds parentheses around nested joins when resolvedChildJoinAttributes is non-empty. The
test expectations show this syntax is generated for SQLite. However, TypeORM supports multiple
database drivers (MySQL, Oracle, SQL Server, PostgreSQL, etc.), and not all support this syntax. The
tests only validate against SQLite, which does support parenthesized joins, but don't verify
compatibility with other databases.

src/query-builder/SelectQueryBuilder.ts[2375-2397]
test/functional/query-builder/select/query-builder-select.test.ts[422-423]
test/functional/query-builder/select/query-builder-select.test.ts[22-22]

Agent Prompt
## Issue Description
The new parenthesized join syntax is not supported by all databases that TypeORM supports, causing query failures on Oracle, SQL Server, and older MySQL versions.

## Issue Context
Parenthesized join syntax (e.g., `LEFT JOIN ( table1 LEFT JOIN table2 ON ... ) ON ...`) is only supported by:
- PostgreSQL: ✓
- SQLite: ✓
- MySQL 8.0.31+: ✓
- MySQL &lt; 8.0.31: ✗
- Oracle: ✗
- SQL Server: ✗

The current implementation always uses parentheses for nested joins without checking database compatibility.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2375-2380]
- src/query-builder/SelectQueryBuilder.ts[2357-2587]

Implement database-specific handling:
1. Check the driver type before adding parentheses
2. For unsupported databases, either:
  - Flatten the join structure (remove nesting)
  - Use subqueries as an alternative
  - Throw a clear error message indicating the limitation
3. Add tests for all supported database types to validate compatibility

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


Grey Divider

Qodo Logo

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (8) 📘 Rule violations (5) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Alias map prototype keys 🐞 Bug ⛨ Security
Description
createJoinExpression builds a join-tree lookup table using a plain object keyed by join aliases, so
aliases like "__proto__"/"constructor" can corrupt the lookup and mis-nest joins or crash join
generation. This is avoidable by using a Map or a null-prototype dictionary for alias indexing.
Code

src/query-builder/SelectQueryBuilder.ts[R2339-2360]

+        const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
+            trees: Array<JoinAttributeTree> // recursive join attribute trees
+            mappedTrees: Record<string, JoinAttributeTree> // flattened lookup join attribute table
+        }>(
+            ({ trees, mappedTrees }, joinAttribute) => {
+                const destinationTableAlias = joinAttribute.alias.name
+
+                const existingTree = joinAttribute.parentAlias
+                    ? mappedTrees[joinAttribute.parentAlias]
+                    : undefined
+                const joinAttributeTree: JoinAttributeTree = {
+                    children: [],
+                    joinAttribute,
+                }
+                if (existingTree) {
+                    existingTree.children.push(joinAttributeTree)
+                } else {
+                    trees.push(joinAttributeTree)
+                }
+
+                mappedTrees[destinationTableAlias] = joinAttributeTree
+
Evidence
The join-tree preprocessing uses mappedTrees: {} and writes `mappedTrees[destinationTableAlias] =
... where destinationTableAlias` is derived from the join alias name. Alias names are provided by
the join API and passed into expressionMap.createAlias({ name: aliasName }) without restriction,
so special keys can collide with Object.prototype and corrupt the lookup.

src/query-builder/SelectQueryBuilder.ts[2332-2364]
src/query-builder/SelectQueryBuilder.ts[2132-2166]

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.createJoinExpression()` indexes join-tree nodes in a plain object (`mappedTrees`) using `joinAttribute.alias.name` as the key. Because alias names come from the public QueryBuilder API, special keys like `__proto__` / `constructor` can corrupt the lookup object and break join nesting.
## Issue Context
This join-tree lookup is used to attach child joins to their parent by alias. Using a prototype-bearing object for attacker-controlled keys is unsafe and can lead to incorrect SQL generation or runtime failures.
## Fix Focus Areas
- Replace `mappedTrees: Record<string, JoinAttributeTree>` with `Map<string, JoinAttributeTree>` (preferred) OR initialize as `Object.create(null)` and access via safe helpers.
- Update reads/writes:
- `mappedTrees[parentAlias]` -> `mappedTrees.get(parentAlias)`
- `mappedTrees[destinationTableAlias] = tree` -> `mappedTrees.set(destinationTableAlias, tree)`
- Add a small regression test that joins with an alias of `"__proto__"` (or similar) and asserts SQL generation does not throw.
### Code references
- src/query-builder/SelectQueryBuilder.ts[2338-2364]

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


2. Misplaced MSSQL lock hints 🐞 Bug ≡ Correctness
Description
When a join has nested child joins, buildJoinClause appends the MSSQL lock hint after the closing
parenthesis, not directly after the table alias as createTableLockExpression documents. With
lockMode enabled on MSSQL and nested joins present, the generated SQL places WITH
(NOLOCK)/(HOLDLOCK, ROWLOCK) in an unexpected location and can break locking behavior or query
parsing.
Code

src/query-builder/SelectQueryBuilder.ts[R2598-2612]

+        const prefix = childJoins ? "(" : ""
+        const postfix = childJoins ? ")" : ""
+        return (
+            " " +
+            direction +
+            " JOIN " +
+            prefix +
+            tableName +
+            " " +
+            this.escape(alias) +
+            childJoins +
+            postfix +
+            this.createTableLockExpression() +
+            (condition ? " ON " + condition : "")
+        )
Evidence
Nested joins now produce parenthesized JOIN groups (so buildJoinClause will set postfix=')').
buildJoinClause concatenates the lock hint after this postfix, while createTableLockExpression’s
doc/example indicates the lock expression belongs immediately after each table clause. MSSQL locking
tests confirm these WITH(...) hints are expected to appear in generated SQL when lock modes are set,
meaning this path is exercised in the codebase.

src/query-builder/SelectQueryBuilder.ts[2591-2612]
src/query-builder/SelectQueryBuilder.ts[2770-2787]
test/functional/query-builder/select/query-builder-select.test.ts[419-424]
test/functional/query-builder/locking/query-builder-locking.test.ts[194-246]

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 nested join parentheses are generated (`childJoins` non-empty), `buildJoinClause` emits the MSSQL lock hint (`WITH (...)`) after the closing `)` of the join group. `createTableLockExpression` documents that the lock hint should be placed right after each table clause (after the table alias), so the current placement is inconsistent and can produce invalid/unexpected MSSQL SQL.
### Issue Context
`createJoinExpression` now groups nested joins using parentheses (e.g., `LEFT JOIN (A ... JOIN B ...) ON ...`). `buildJoinClause` is responsible for composing each JOIN fragment.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2591-2612]
- src/query-builder/SelectQueryBuilder.ts[2770-2787]

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


3. Typo: createJoinTreeRecursivly should be Recursively ✓ Resolved 📘 Rule violation ≡ Correctness
Description
• The method name createJoinTreeRecursivly contains a spelling error - it should be
createJoinTreeRecursively (with an 'e'). • This violates the project's naming conventions as other
similar methods in the codebase use the correct spelling Recursively (e.g.,
createEmbeddedsRecursively, applyRelationsRecursively). • Consistent naming is important for
code maintainability and professionalism.
Code

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

+    protected createJoinTreeRecursivly({
Evidence
The compliance checklist requires all new identifiers to follow established naming patterns. A
search of the codebase reveals that the correct spelling 'Recursively' is used consistently in other
methods like createEmbeddedsRecursively and applyRelationsRecursively. The new method name uses
'Recursivly' which is a misspelling and deviates from the project's established naming convention.

Rule 1: Consistent Naming Conventions
src/query-builder/SelectQueryBuilder.ts[2459-2459]
src/metadata-builder/EntityMetadataBuilder.ts[855-855]

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 method name `createJoinTreeRecursivly` contains a spelling error and should be renamed to `createJoinTreeRecursively` to match the project&amp;amp;amp;amp;amp;amp;#x27;s naming conventions.
## Issue Context
The codebase consistently uses the correct spelling &amp;amp;amp;amp;amp;amp;#x27;Recursively&amp;amp;amp;amp;amp;amp;#x27; in similar method names like `createEmbeddedsRecursively` and `applyRelationsRecursively`. This typo violates the Consistent Naming Conventions compliance rule.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2453-2453]
- src/query-builder/SelectQueryBuilder.ts[2459-2459]
- src/query-builder/SelectQueryBuilder.ts[2473-2473]

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


View more (1)
4. Incorrect Tree Building for Root Joins ✓ Resolved 🐞 Bug ≡ Correctness
Description
• The tree-building logic incorrectly groups all joins without a parent alias under a single
'parentless' key, causing independent root-level joins to be nested as children of each other
instead of being siblings • When multiple independent joins exist on the main table (e.g.,
.leftJoin('post.tag', 'tag').leftJoin('post.author', 'author')), the second and subsequent joins are
incorrectly added as children of the first join • This results in malformed SQL with incorrect join
hierarchy and parentheses placement, breaking queries with multiple independent root joins
Code

src/query-builder/SelectQueryBuilder.ts[R2431-2443]

+                const parentAlias = joinAttribute.parentAlias || "parentless"
+                const destinationTableAlias = joinAttribute.alias.name
+
+                const existingTree = mappedTrees[parentAlias]
+                const joinAttributeTree: JoinAttributeTree = {
+                    children: [],
+                    joinAttribute,
+                }
+                if (existingTree) {
+                    existingTree.children.push(joinAttributeTree)
+                } else {
+                    trees.push(joinAttributeTree)
+                }
Evidence
The reduce function uses 'parentless' as a shared key for all joins without a parentAlias. When
processing the first join without a parent (e.g., 'post.tag'), it creates a new tree and stores it
in mappedTrees['parentless']. When processing the second independent join (e.g., 'post.author'),
existingTree = mappedTrees['parentless'] finds the first join's tree, and the code incorrectly adds
the second join as a child via existingTree.children.push(joinAttributeTree). This is wrong because
'post.tag' and 'post.author' should be sibling joins at the root level, not parent-child. The
correct approach would be to check if the parentAlias matches the actual parent of the current join,
not use a generic 'parentless' string that conflates all root-level joins.

src/query-builder/SelectQueryBuilder.ts[2431-2443]
test/functional/query-builder/join/query-builder-joins.test.ts[79-82]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The tree-building algorithm incorrectly groups all joins without a parentAlias under a single &amp;amp;amp;amp;amp;amp;#x27;parentless&amp;amp;amp;amp;amp;amp;#x27; key, causing independent root-level joins to be nested as children instead of siblings.
## Issue Context
When processing joins like .leftJoin(&amp;amp;amp;amp;amp;amp;#x27;post.tag&amp;amp;amp;amp;amp;amp;#x27;, &amp;amp;amp;amp;amp;amp;#x27;tag&amp;amp;amp;amp;amp;amp;#x27;).leftJoin(&amp;amp;amp;amp;amp;amp;#x27;post.author&amp;amp;amp;amp;amp;amp;#x27;, &amp;amp;amp;amp;amp;amp;#x27;author&amp;amp;amp;amp;amp;amp;#x27;), both have parentAlias=&amp;amp;amp;amp;amp;amp;#x27;post&amp;amp;amp;amp;amp;amp;#x27; but the current code treats them as having no parent and groups them under &amp;amp;amp;amp;amp;amp;#x27;parentless&amp;amp;amp;amp;amp;amp;#x27;, causing the second to become a child of the first.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2426-2450] - Modify the reduce function to properly handle root-level joins as separate tree entries instead of grouping them under &amp;amp;amp;amp;amp;amp;#x27;parentless&amp;amp;amp;amp;amp;amp;#x27;

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



Remediation recommended

5. Manual joins not nested 🐞 Bug ≡ Correctness
Description
createJoinExpression nests joins only when joinAttribute.parentAlias is present, so manual joins
created via table/entity targets (not alias-property syntax) are emitted as a flat join list. When
an INNER JOIN depends on a prior LEFT JOIN only through its ON condition, the query can still
return 0 rows by filtering out the LEFT-joined side.
Code

src/query-builder/SelectQueryBuilder.ts[R2339-2353]

+            ({ trees, mappedTrees }, joinAttribute) => {
+                const destinationTableAlias = joinAttribute.alias.name
+
+                const existingTree = joinAttribute.parentAlias
+                    ? mappedTrees[joinAttribute.parentAlias]
+                    : undefined
+                const joinAttributeTree: JoinAttributeTree = {
+                    children: [],
+                    joinAttribute,
+                }
+                if (existingTree) {
+                    existingTree.children.push(joinAttributeTree)
+                } else {
+                    trees.push(joinAttributeTree)
+                }
Evidence
Nesting is decided exclusively by joinAttribute.parentAlias during tree construction; for manual
joins, parentAlias is undefined because it only exists for alias-property strings, so dependent
INNER JOINs are not grouped under the LEFT JOIN they rely on and can still filter out LEFT-joined
rows.

src/query-builder/SelectQueryBuilder.ts[2333-2356]
src/query-builder/JoinAttribute.ts[120-134]
src/query-builder/QueryBuilderUtils.ts[11-26]
src/query-builder/SelectQueryBuilder.ts[2079-2163]

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.createJoinExpression()` builds a join nesting tree solely via `JoinAttribute.parentAlias`. For joins created with table/entity targets (e.g. `leftJoin("table", "t", ...)`), `parentAlias` is `undefined`, so subsequent dependent joins expressed via `ON` conditions cannot be nested under the correct LEFT JOIN group.
## Issue Context
- `JoinAttribute.parentAlias` is derived only from alias-property syntax (`QueryBuilderUtils.isAliasProperty()`), not from join conditions.
- `SelectQueryBuilder.join()` explicitly supports `entityOrProperty` as `Function | string | (qb)=>qb`, so manual joins are a supported API shape.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2333-2360]
- src/query-builder/SelectQueryBuilder.ts[2079-2163]
- src/query-builder/JoinAttribute.ts[120-134]
- src/query-builder/QueryBuilderUtils.ts[11-26]
Potential implementation direction: when `parentAlias` is missing, derive the parent join for nesting from the join condition (e.g., detect referenced aliases and associate the join with the most recent matching alias / explicitly track parent when building the join attribute), so LEFT-join wrapping also works for manual joins.

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


6. Recursive join stack overflow 🐞 Bug ☼ Reliability
Description
SelectQueryBuilder.createJoinTreeRecursively renders joins via unbounded recursion, so sufficiently
deep join nesting can throw "RangeError: Maximum call stack size exceeded" and fail query
generation. This is a new failure mode compared to the prior iterative join rendering approach.
Code

src/query-builder/SelectQueryBuilder.ts[R2385-2389]

+        const childJoins = (children || [])
+            .map((joinTreeChild) => {
+                return this.createJoinTreeRecursively(joinTreeChild)
+            })
+            .join(" ")
Evidence
The join SQL is produced by recursively calling createJoinTreeRecursively for each child; there is
no depth guard or iterative traversal, so very deep nesting can overflow the JS stack.

src/query-builder/SelectQueryBuilder.ts[2373-2390]

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

## Issue description
`createJoinTreeRecursively` walks the join tree using recursion. With a deeply nested join structure (e.g., user-generated or programmatically generated joins), this can exceed the JavaScript call stack and crash query generation.
### Issue Context
TypeORM can generate many joins via nested relations and/or dynamic query builder usage. Introducing an unbounded recursive traversal adds a potential runtime failure mode (`RangeError`) for deep trees.
### Fix Focus Areas
- Convert the recursive join-tree emission to an explicit stack/iterative DFS that builds the SQL string without recursive calls.
- Ensure output SQL is identical to the current behavior for typical join depths.
#### Relevant code
- src/query-builder/SelectQueryBuilder.ts[2337-2371]
- src/query-builder/SelectQueryBuilder.ts[2373-2390]
- src/query-builder/SelectQueryBuilder.ts[2566-2587]

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


7. Brittle join-count regex 🐞 Bug ☼ Reliability
Description
The eager-relations test now counts user joins with a regex that won’t match schema-qualified table
paths (e.g. "dbo"."user"), so the assertion can undercount joins and fail on some drivers even when
the query is correct.
Code

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[R236-238]

+                const userJoinCount = (
+                    sql.match(/LEFT JOIN \(?."?user"?/gi) ?? []
+                ).length
Evidence
The test runs across all configured drivers, but TypeORM builds EntityMetadata.tablePath via
driver.buildTableName(tableName, schema, database), and QueryBuilder.getTableName escapes each
dot-separated segment. That means generated SQL can legally contain schema-qualified `... JOIN
"schema"."user" ..., which the current regex does not match (it expects LEFT JOIN ("user"
...)`-style patterns).

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[15-23]
test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts[219-239]
src/metadata/EntityMetadata.ts[1072-1076]
src/query-builder/QueryBuilder.ts[642-650]

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 test asserts the number of `user` joins by regex-matching the generated SQL:

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


View more (8)
8. normalizeNumber() uses any 📘 Rule violation ⚙ Maintainability
Description
QueryBuilder.normalizeNumber accepts num: any, which bypasses TypeScript type-safety and is
inconsistent with the rule to avoid any usage to work around typing. This can mask incorrect call
sites and make future refactors/error-checking harder.
Code

src/query-builder/QueryBuilder.ts[R1737-1742]

+    protected normalizeNumber(num: any) {
+        if (typeof num === "number" || num === undefined || num === null)
+            return num
+
+        return Number(num)
+    }
Evidence
PR Compliance ID 4 requires avoiding any usage that bypasses types. The added helper method
explicitly types its input as any (protected normalizeNumber(num: any)), which is exactly the
prohibited pattern.

Rule 4: Remove AI-generated noise
src/query-builder/QueryBuilder.ts[1737-1742]

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

## Issue description
`normalizeNumber` is introduced with a parameter typed as `any`, which undermines type-safety and violates the project guidance to avoid `any` used to bypass typing.
## Issue Context
This helper is in `QueryBuilder` (a core base class) and will be reused broadly, so using `any` here propagates weak typing across the query-builder surface area.
## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1737-1742]

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


9. Semicolon checks removed 🐞 Bug ⛨ Security
Description
SelectQueryBuilder.groupBy/addGroupBy no longer reject semicolons, and the resulting GROUP BY SQL is
concatenated directly into the query string and executed by drivers unchanged. This removes prior
defense-in-depth against statement-separator fragments reaching QueryRunner.query.
Code

src/query-builder/SelectQueryBuilder.ts[R1367-1370]

groupBy(groupBy?: string): this {
if (groupBy) {
-            this.assertNoSemicolon(groupBy, "groupBy")
  this.expressionMap.groupBys = [groupBy]
} else {
Evidence
groupBy now stores the provided string directly, and createGroupByExpression concatenates
groupBys without escaping/sanitization. The query runner executes the final query string via
databaseConnection.query(query, parameters), and the SQL-injection test file no longer contains
the prior semicolon-rejection coverage, indicating the guardrail was intentionally removed in this
PR.

src/query-builder/SelectQueryBuilder.ts[1358-1384]
src/query-builder/SelectQueryBuilder.ts[2590-2596]
src/driver/postgres/PostgresQueryRunner.ts[256-276]
test/functional/query-builder/sql-injection/sql-injection.test.ts[44-86]

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

## Issue description
Semicolon validation was removed from raw-SQL fragment entry points like `groupBy` / `addGroupBy` (and similarly in other builder APIs). Since `createGroupByExpression()` concatenates these fragments directly, semicolon-containing input can now flow into the final SQL.
## Issue Context
While these APIs accept raw SQL fragments by design, rejecting statement separators was a useful guardrail and was previously covered by functional tests. The PR removes that guardrail without an alternative.
## Fix Focus Areas
- Re-introduce a lightweight semicolon / statement-separator guard for raw fragment setters (at least `groupBy`/`addGroupBy`; consider consistency across `select`/`addSelect` too).
- Alternatively, explicitly document the change and add targeted tests verifying behavior across drivers.
### Code references
- src/query-builder/SelectQueryBuilder.ts[1366-1384]
- src/query-builder/SelectQueryBuilder.ts[2593-2596]

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


10. Array style inconsistent 📘 Rule violation ⚙ Maintainability
Description
New types use Array while the surrounding file predominantly uses T[] array syntax, making the
change stylistically inconsistent. This adds avoidable inconsistency in a core query-builder file.
Code

src/query-builder/SelectQueryBuilder.ts[R2395-2397]

+        const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
+            trees: Array<JoinAttributeTree> // recursive join attribute trees
+            mappedTrees: Record<string, JoinAttributeTree> // flattened lookup join attribute table
Evidence
The checklist requires avoiding style inconsistencies; the added Array annotations introduce a
different array-typing style than the rest of SelectQueryBuilder.ts. The cited lines show the new
Array usages.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[48-51]
src/query-builder/SelectQueryBuilder.ts[2395-2397]

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

## Issue description
New code uses `Array<JoinAttributeTree>` array typing which is inconsistent with the predominant `T[]` style used throughout `src/query-builder/SelectQueryBuilder.ts`.
## Issue Context
The compliance checklist requires avoiding style inconsistencies in added code.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[48-51]
- src/query-builder/SelectQueryBuilder.ts[2395-2397]

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


11. Redundant (children || []) fallback 📘 Rule violation ⚙ Maintainability
Description
children is always present per the JoinAttributeTree interface, but the code adds a defensive
(children || []) fallback anyway. This introduces unnecessary defensive noise inconsistent with
the rest of the file.
Code

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

+        const childJoins = (children || [])
Evidence
The checklist disallows abnormal defensive checks/noise; the added (children || []) is redundant
given JoinAttributeTree.children is not optional. The cited line shows the new defensive fallback.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[2441-2445]
src/query-builder/SelectQueryBuilder.ts[48-51]

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

## Issue description
`createJoinTreeRecursively` uses `(children || [])` even though `children` is required by the `JoinAttributeTree` interface.
## Issue Context
This is unnecessary defensive code and adds style noise in a core query-builder path.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2429-2445]

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


12. Nested join alias scope 🐞 Bug ≡ Correctness
Description
Nesting child joins into parenthesized join groups changes alias visibility: user-provided
joinAttr.condition strings on nested child joins can no longer legally reference aliases outside
the parentheses, so queries that relied on cross-alias join conditions may now generate invalid SQL
and fail.
Code

src/query-builder/SelectQueryBuilder.ts[R2436-2459]

+        let appendedCondition = joinAttr.condition
+            ? " AND (" + joinAttr.condition + ")"
+            : ""
+        const parentAlias = joinAttr.parentAlias
+
+        const childJoins = (children || [])
+            .map((joinTreeChild) => {
+                return this.createJoinTreeRecursively(joinTreeChild)
+            })
+            .join(" ")
+
+        // if join was build without relation (e.g. without "post.category") then it means that we have direct
+        // table to join, without junction table involved. This means we simply join direct table.
+        if (!parentAlias || !relation) {
+            const destinationJoin = joinAttr.alias.subQuery
+                ? joinAttr.alias.subQuery
+                : this.getTableName(destinationTableName)
+            return this.buildJoinClause(
+                joinAttr.direction,
+                destinationJoin,
+                destinationTableAlias,
+                joinAttr.condition || "",
+                childJoins,
+            )
Evidence
The PR now emits child joins as part of a parenthesized join group via childJoins recursion, and
user-provided join conditions are appended directly into the nested join's ON clause
(appendedCondition). TypeORM's join API accepts arbitrary condition strings (no alias-scope
validation) and the test suite already demonstrates join conditions referencing other aliases;
moving such a join into a nested join group can make those referenced aliases out-of-scope for that
ON clause in SQL.

src/query-builder/SelectQueryBuilder.ts[2429-2460]
src/query-builder/SelectQueryBuilder.ts[2631-2643]
src/query-builder/SelectQueryBuilder.ts[2144-2172]
test/functional/query-builder/join/query-builder-joins.test.ts[654-664]

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 new nested join rendering moves child joins inside a parenthesized join group. If a user provides a join condition for a nested child join that references an alias outside that group (e.g., the main alias), the generated SQL can become invalid due to alias scoping rules.
### Issue Context
- `join(..., condition?: string)` accepts arbitrary SQL fragments.
- `createJoinTreeRecursively` nests child joins and appends `joinAttr.condition` into the nested join's ON clause.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2429-2460]
- src/query-builder/SelectQueryBuilder.ts[2393-2427]
### Fix directions (pick one)
- **Safer rendering:** Only nest child joins when it is safe (e.g., when the child join has no extra user condition, or when the condition only references the parent/child aliases).
- **Alternative SQL structure:** For left-join + inner-join elimination cases, use a derived-table/subquery approach that preserves needed alias visibility.
- **Add a regression test:** Construct a query with `leftJoinAndSelect(parent)` + `innerJoinAndSelect(child, ..., '<child cond referencing main alias>')` and assert it still executes/produces valid SQL for at least one driver.

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


13. Missing documentation for join wrapping behavior 📘 Rule violation ≡ Correctness
Description
• This PR fixes a 6-year-old issue (#3080) that changes how LEFT JOIN and INNER JOIN are combined in
generated SQL queries. • The fix introduces parentheses wrapping for child joins, which is a
significant user-facing change in query generation behavior. • No documentation updates were
included to explain this new behavior, how it affects existing queries, or when the wrapping occurs.
Code

src/query-builder/SelectQueryBuilder.ts[R2425-2457]

+        // preprocess join attributes by nesting them when necessary
+        const joinAttributeTrees = this.expressionMap.joinAttributes.reduce<{
+            trees: Array<JoinAttributeTree> // recursive join attribute trees
+            mappedTrees: Record<string, JoinAttributeTree> // flattened lookup join attribute table
+        }>(
+            ({ trees, mappedTrees }, joinAttribute) => {
+                const parentAlias = joinAttribute.parentAlias || "parentless"
+                const destinationTableAlias = joinAttribute.alias.name
+
+                const existingTree = mappedTrees[parentAlias]
+                const joinAttributeTree: JoinAttributeTree = {
+                    children: [],
+                    joinAttribute,
+                }
+                if (existingTree) {
+                    existingTree.children.push(joinAttributeTree)
+                } else {
+                    trees.push(joinAttributeTree)
+                }
+
+                mappedTrees[destinationTableAlias] = joinAttributeTree
+
+                return { trees, mappedTrees }
+            },
+            { trees: [], mappedTrees: {} },
+        )
+
+        const joinStatements = joinAttributeTrees.trees.map((joinTree) => {
+            return this.createJoinTreeRecursivly(joinTree)
+        })
+
+        return joinStatements.join(" ")
+    }
Evidence
The compliance checklist requires documentation updates for user-facing changes. The PR description
explicitly states this fixes issue #3080 and shows SQL query output changes with parentheses
wrapping. The test file updates in query-builder-select.test.ts show expected SQL output changing
from flat joins to wrapped joins with parentheses. However, no documentation files in
docs/docs/query-builder/ were modified to explain this behavior change to users.

Rule 2: Docs updated for user-facing changes
test/functional/query-builder/select/query-builder-select.test.ts[422-423]

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 a significant change to how TypeORM generates SQL for queries with LEFT JOIN followed by INNER JOIN. The generated SQL now wraps child joins in parentheses to prevent incorrect filtering. This user-facing behavior change needs to be documented.
## Issue Context
This fixes issue #3080 where INNER JOINs to LEFT JOINed tables would incorrectly return 0 rows. The fix wraps child joins in parentheses to maintain correct SQL semantics. Users may notice different SQL output in their query logs and should understand why this happens.
## Fix Focus Areas
- docs/docs/query-builder/1-select-query-builder.md[686-750]

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


14. Tests not in functional suite with issue reference 📘 Rule violation ≡ Correctness
Description
• The PR adds two new test cases for the LEFT JOIN + INNER JOIN fix in the functional test suite. •
However, the tests lack a comment referencing issue #3080, which would help future maintainers
understand why these specific test cases exist. • The compliance rule recommends adding issue
references in test comments when fixing specific issues.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[R299-342]

+        it("should load results from a left join with a child inner join both of which have zero results", () =>
+            Promise.all(
+                connections.map(async (connection) => {
+                    const post = new Post()
+                    post.title = "about BMW"
+                    await connection.manager.save(post)
+
+                    const loadedPost = await connection.manager
+                        .createQueryBuilder(Post, "post")
+                        .leftJoinAndSelect("post.categories", "categories")
+                        .innerJoinAndSelect("categories.images", "images")
+                        .where("post.id = :id", { id: post.id })
+                        .getOne()
+
+                    expect(loadedPost!).to.not.be.null
+                    expect(loadedPost!.categories).to.be.eql([])
+                    expect(loadedPost!.categories.length).to.be.equal(0)
+                }),
+            ))
+
+        it("should load results from a left join with a child inner join that has zero results", () =>
+            Promise.all(
+                connections.map(async (connection) => {
+                    const category = new Category()
+                    category.name = "germany"
+                    await connection.manager.save(category)
+
+                    const post = new Post()
+                    post.title = "about BMW"
+                    post.categories = [category]
+                    await connection.manager.save(post)
+
+                    const loadedPost = await connection.manager
+                        .createQueryBuilder(Post, "post")
+                        .leftJoinAndSelect("post.categories", "categories")
+                        .innerJoinAndSelect("categories.images", "images")
+                        .where("post.id = :id", { id: post.id })
+                        .getOne()
+
+                    expect(loadedPost!).to.not.be.null
+                    expect(loadedPost!.categories).to.be.eql([])
+                    expect(loadedPost!.categories.length).to.be.equal(0)
+                }),
+            ))
Evidence
The compliance checklist states that issue fixes should add tests to test/functional with an issue
reference in the test comment when applicable. The PR adds two new tests to the functional suite
(which is good), but they don't include a comment referencing issue #3080. The PR description
explicitly states this fixes issue #3080, so adding a reference comment would help future
maintainers understand the context of these tests.

Rule 3: Prefer functional tests over per-issue tests
test/functional/query-builder/join/query-builder-joins.test.ts[299-317]

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 new test cases for LEFT JOIN + INNER JOIN behavior lack a comment referencing the original issue #3080 that they fix.
## Issue Context
This PR fixes a 6-year-old issue where INNER JOINs to LEFT JOINed tables would return 0 rows. Adding a comment reference helps future maintainers understand why these specific test cases exist and what issue they prevent from regressing.
## Fix Focus Areas
- test/functional/query-builder/join/query-builder-joins.test.ts[299-299]
- test/functional/query-builder/join/query-builder-joins.test.ts[319-319]

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


15. Non-Standard SQL Parentheses Syntax 🐞 Bug ≡ Correctness
Description
• The implementation wraps nested joins in parentheses around table references, creating SQL like
'LEFT JOIN ( "post" "posts" ... ) ON ...' • This syntax is non-standard and may not be supported by
all database engines (PostgreSQL, MySQL, SQL Server, Oracle) • While SQLite (used in tests) may
accept this syntax, it could cause failures on other databases, limiting portability
Code

src/query-builder/SelectQueryBuilder.ts[R2477-2504]

+        const resolvedChildJoinAttributesPrefix = resolvedChildJoinAttributes
+            ? "( "
+            : ""
+        const resolvedChildJoinAttributesPostfix = resolvedChildJoinAttributes
+            ? " )"
+            : ""
+
+        // if join was build without relation (e.g. without "post.category") then it means that we have direct
+        // table to join, without junction table involved. This means we simply join direct table.
+        if (!parentAlias || !relation) {
+            const destinationJoin = joinAttr.alias.subQuery
+                ? joinAttr.alias.subQuery
+                : this.getTableName(destinationTableName)
+            return (
+                " " +
+                joinAttr.direction +
+                " JOIN " +
+                resolvedChildJoinAttributesPrefix +
+                destinationJoin +
+                " " +
+                this.escape(destinationTableAlias) +
+                resolvedChildJoinAttributes +
+                resolvedChildJoinAttributesPostfix +
+                this.createTableLockExpression() +
+                (joinAttr.condition
+                    ? " ON " + this.replacePropertyNames(joinAttr.condition)
+                    : "")
+            )
Evidence
The code generates parentheses prefix/postfix strings and wraps them around table names in JOIN
clauses. The test expectations confirm this is the intended output, showing SQL like 'LEFT JOIN (
"post" "posts" LEFT JOIN "category" "category" ON ... ) ON ...'. While this may work in SQLite (the
test database), standard SQL JOIN syntax does not support parentheses wrapping individual table
references in this manner. Most production databases expect sequential JOINs without such
parentheses. This creates a portability risk.

src/query-builder/SelectQueryBuilder.ts[2477-2482]
src/query-builder/SelectQueryBuilder.ts[2490-2504]
test/functional/query-builder/select/query-builder-select.test.ts[422-423]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The generated SQL includes parentheses around nested joins in a non-standard way that may not be supported by all database engines.
## Issue Context
The code generates SQL like &amp;amp;amp;amp;amp;amp;#x27;LEFT JOIN ( &amp;amp;amp;amp;amp;amp;quot;post&amp;amp;amp;amp;amp;amp;quot; &amp;amp;amp;amp;amp;amp;quot;posts&amp;amp;amp;amp;amp;amp;quot; LEFT JOIN &amp;amp;amp;amp;amp;amp;quot;category&amp;amp;amp;amp;amp;amp;quot; ... ) ON ...&amp;amp;amp;amp;amp;amp;#x27;. Standard SQL uses sequential JOINs without such parentheses. This may cause failures on PostgreSQL, MySQL, SQL Server, and Oracle.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2477-2482] - Remove or modify the parentheses prefix/postfix logic
- src/query-builder/SelectQueryBuilder.ts[2490-2504] - Update the return statement to generate standard sequential JOIN syntax
- src/query-builder/SelectQueryBuilder.ts[2526-2539] - Update ManyToOne/OneToOneOwner join generation
- src/query-builder/SelectQueryBuilder.ts[2579-2592] - Update OneToMany/OneToOneNotOwner join generation
- src/query-builder/SelectQueryBuilder.ts[2663-2687] - Update ManyToMany join generation

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



Informational

16. Misleading join test name ✓ Resolved 🐞 Bug ≡ Correctness
Description
A newly added test claims it covers a left join with a child inner join, but the test body only
executes a simple many-to-one leftJoinAndSelect on post.tag. This mismatch makes the test intent
unclear and can mislead future maintenance.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[R382-393]

+        it("should load results from a many-to-one left join with a child inner join that has zero results", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    const post = new Post()
+                    post.title = "about dogs"
+                    await dataSource.manager.save(post)
+
+                    const loadedPost = await dataSource.manager
+                        .createQueryBuilder(Post, "post")
+                        .leftJoinAndSelect("post.tag", "tag")
+                        .where("post.id = :id", { id: post.id })
+                        .getOne()
Evidence
The test name mentions a “child inner join”, but the query contains only a single leftJoinAndSelect
and no innerJoin/innerJoinAndSelect call.

test/functional/query-builder/join/query-builder-joins.test.ts[382-393]

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 test name states it covers a left join with a child inner join, but the test query only performs a single `leftJoinAndSelect(&quot;post.tag&quot;, &quot;tag&quot;)`.
### Issue Context
This is a newly added functional test and will be used as documentation for the intended behavior.
### Fix Focus Areas
- test/functional/query-builder/join/query-builder-joins.test.ts[382-393]

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


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

Comment thread src/query-builder/SelectQueryBuilder.ts Resolved
Comment thread src/query-builder/SelectQueryBuilder.ts Resolved
@pkuczynski pkuczynski self-assigned this Mar 17, 2026
# Conflicts:
#	src/query-builder/SelectQueryBuilder.ts
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 608f127

@pkuczynski pkuczynski changed the title fix: fix up inner join wrapping left joined tables fix(query-builder): wrap inner joins nested under left joins to prevent result elimination Mar 17, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 5d40f5a

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

Copy link
Copy Markdown

Persistent review updated to latest commit c7495bd

…join

# Conflicts:
#	src/query-builder/SelectQueryBuilder.ts
#	test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.test.ts
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 2c6bb5d

@pkuczynski pkuczynski changed the title fix(query-builder): wrap inner joins nested under left joins to prevent result elimination fix(query-builder): wrap inner joins under left joins correctly Apr 11, 2026
@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 27f6c8e

@Cprakhar

Cprakhar commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

I can't test spanner locally for the currently failing tests, so I'm leaving it for someone else to pick up.

@alumni

alumni commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

I can't test spanner locally for the currently failing tests, so I'm leaving it for someone else to pick up.

@Cprakhar it's the typical issue when checking arrays - the order is important (the two posts are swapped). There are 2 more failing assertions at :843:75 and :1329:75. Will check later.

@alumni
alumni enabled auto-merge (squash) June 18, 2026 17:40
@alumni

alumni commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the fix @harm-less!

This will make it in the next patch release (1.0.1).

@alumni
alumni merged commit d5f4b9d into typeorm:master Jun 18, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Jun 18, 2026
@harm-less

Copy link
Copy Markdown
Contributor Author

@alumni That's great to hear, thank you!

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

Development

Successfully merging this pull request may close these issues.

Inner joining to left joined table returns 0 rows

6 participants