Skip to content

fix: fix up limit with joins - #11987

Merged
gioboa merged 2 commits into
typeorm:masterfrom
gioboa:fix/3967
Feb 14, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
gioboa:fix/3967

Conversation

@gioboa

@gioboa gioboa commented Feb 13, 2026

Copy link
Copy Markdown
Collaborator

Close #3967

Description of change

Pull-Request Checklist

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

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

Copy link
Copy Markdown

User description

Close #3967

Description of change

Pull-Request Checklist

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

PR Type

Bug fix


Description

  • Fix pagination with joins by supporting limit/offset in addition to take/skip

  • Clear limit/offset from inner queries to prevent double pagination

  • Add test case validating correct result count with limit and left joins


Diagram Walkthrough

flowchart LR
  A["Query with limit/offset<br/>and joins"] -->|Check pagination<br/>condition| B["Include limit/offset<br/>in condition"]
  B -->|Clone query| C["Inner query<br/>for distinct IDs"]
  C -->|Clear limit/offset| D["Outer query<br/>applies pagination"]
  D -->|Second query| E["Load results<br/>without pagination"]
Loading

File Walkthrough

Relevant files
Bug fix
SelectQueryBuilder.ts
Support limit/offset in pagination with joins                       

src/query-builder/SelectQueryBuilder.ts

  • Extended pagination condition check to include limit and offset
    properties alongside take and skip
  • Clear limit and offset from inner distinct query to prevent double
    pagination
  • Use nullish coalescing to fallback from take/skip to limit/offset in
    outer query
  • Clear limit and offset from second query before loading raw results
+14/-5   
Tests
Photo.ts
Add Photo entity for join testing                                               

test/functional/query-builder/join/entity/Photo.ts

  • New entity class representing a Photo with id, name, and many-to-one
    relationship to User
  • Establishes the relationship side for testing joins with multiple
    related records
+19/-0   
User.ts
Add one-to-many relationship to User                                         

test/functional/query-builder/join/entity/User.ts

  • Add OneToMany relationship to Photo entity
  • Refactor imports to use barrel import from source root
  • Add photos property to User entity
+10/-3   
query-builder-joins.test.ts
Add test for limit with left joins                                             

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

  • Import new Photo entity
  • Add comprehensive test case for limit with left joins
  • Test verifies correct number of results (1 user) and correct number of
    related photos (2) when using limit
+41/-0   

@pkg-pr-new

pkg-pr-new Bot commented Feb 13, 2026 •

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

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

commit: a64b6ad

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to a64b6ad

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent double-applied pagination

Clear skip and take properties on the inner query clone, in addition to limit
and offset, to prevent applying pagination twice and ensure correct results.

src/query-builder/SelectQueryBuilder.ts [3630-3634]

 const originalQuery = this.clone()
 
-// clear limit/offset from the inner query since pagination is handled by the outer distinct query
+// clear pagination from the inner query since pagination is handled by the outer distinct query
 originalQuery.expressionMap.limit = undefined
 originalQuery.expressionMap.offset = undefined
+originalQuery.expressionMap.take = undefined
+originalQuery.expressionMap.skip = undefined
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a bug in the PR where skip and take are not cleared from the inner query, which would lead to incorrect pagination results.

High
Avoid re-pagination in fetch query

Clear skip and take properties on the second query clone, in addition to limit
and offset, to prevent re-applying pagination and ensure all requested entities
are fetched.

src/query-builder/SelectQueryBuilder.ts [3716-3723]

 const secondQuery = this.clone()
     .mergeExpressionMap({
         extraAppendedAndWhereCondition: condition,
     })
     .setParameters(parameters)
 secondQuery.expressionMap.limit = undefined
 secondQuery.expressionMap.offset = undefined
+secondQuery.expressionMap.take = undefined
+secondQuery.expressionMap.skip = undefined
 rawResults = await secondQuery.loadRawResults(queryRunner)
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly points out a bug where skip and take are not cleared from the second query, which would cause incorrect pagination and fewer results than expected.

High
  • More

Previous suggestions

Suggestions up to commit c51d280
CategorySuggestion                                                                                                                                    Impact
Possible issue
Clear all pagination on inner query

In addition to clearing limit and offset on the inner query's expression map,
also clear the legacy take and skip fields to prevent potential residual
pagination issues.

src/query-builder/SelectQueryBuilder.ts [3635-3636]

 originalQuery.expressionMap.limit = undefined
 originalQuery.expressionMap.offset = undefined
+originalQuery.expressionMap.take = undefined
+originalQuery.expressionMap.skip = undefined
Suggestion importance[1-10]: 7

__

Why: This is a good suggestion for defensive programming. Clearing the legacy skip and take properties on the cloned query ensures that no residual pagination values interfere with the subquery logic, improving robustness.

Medium
Clear pagination on second query

In addition to resetting limit and offset on the second cloned query, also reset
take and skip to ensure no unintended pagination is applied.

src/query-builder/SelectQueryBuilder.ts [3723-3724]

 secondQuery.expressionMap.limit = undefined
 secondQuery.expressionMap.offset = undefined
+secondQuery.expressionMap.take = undefined
+secondQuery.expressionMap.skip = undefined
Suggestion importance[1-10]: 7

__

Why: This is a good suggestion for defensive programming. Clearing the legacy skip and take properties on the second cloned query ensures that no residual pagination values are applied, making the code more robust.

Medium

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

✅ 1. limit(1) test too weak 📎 Requirement gap ✓ Correctness
Description
The new regression test uses .limit(1) and only validates a single returned entity, so it does not
cover the reported Postgres joins+limit failure mode where .getMany() returns fewer entities than
the LIMIT (e.g., limit(5) yielding 1). It also does not verify that .execute() and
.getMany() (or direct SQL execution) return consistent counts for the same generated query,
leaving compliance requirements 5–7 unverified.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[R1719-1723]

+                const users = await manager
+                    .createQueryBuilder(User, "user")
+                    .leftJoinAndSelect("user.photos", "photo")
+                    .limit(1)
+                    .getMany()
Evidence
Compliance IDs 5–7 require verifying that join queries with limit(N) return N entities via
.getMany(), and that .execute()/direct SQL results do not diverge from .getMany() on Postgres.
The added test hard-codes .limit(1) and asserts only one entity is returned, and it does not
compare .execute()/direct SQL result counts to .getMany().

QueryBuilder getMany() must honor limit() when joins/relations are present (Postgres)
Results returned by getMany() must be consistent with executing the generated SQL directly (Postgres, joins + limit)
execute() and getMany() must not diverge on result count for join queries with limit() (Postgres)
test/functional/query-builder/join/query-builder-joins.test.ts[1690-1726]

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 uses `.limit(1)` and does not verify the Postgres-specific joins+limit regression described by the compliance requirements (e.g., `limit(5)` returning fewer entities than requested). It also does not check that `.execute()`/direct SQL execution yields the same effective result count as `.getMany()`.
## Issue Context
Compliance IDs 5–7 require demonstrating that, for a join query with `limit(5)`, `.getMany()` returns 5 entities and does not diverge from `.execute()` or running the generated SQL directly (Postgres).
## Fix Focus Areas
- test/functional/query-builder/join/query-builder-joins.test.ts[1690-1727]ൃത

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



Remediation recommended

✅ 2. Outdated limit/offset docs 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder.limit()/offset() JSDoc says these may not work with joins and recommends
using take/skip. This PR explicitly adds limit/offset support to the join+pagination two-query
flow (and adds a test), so the docs are now misleading for entity-loading queries.
Code

src/query-builder/SelectQueryBuilder.ts[R3591-3594]

+            (this.expressionMap.skip ||
+                this.expressionMap.take ||
+                this.expressionMap.offset ||
+                this.expressionMap.limit) &&
Evidence
The PR extends the pagination-with-joins branch to trigger when offset/limit are set, and the new
functional test demonstrates leftJoinAndSelect(...).limit(1).getMany() is now expected to work
correctly. However, the method-level docs still say limit/offset may not work with joins and
instruct users to use take/skip, which is no longer accurate for this code path.

src/query-builder/SelectQueryBuilder.ts[3590-3596]
src/query-builder/SelectQueryBuilder.ts[1534-1539]
test/functional/query-builder/join/query-builder-joins.test.ts[1690-1727]

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.limit()` / `offset()` documentation currently warns that these APIs may not work as expected with joins and recommends `take/skip`. This PR adds support for `limit/offset` in the join pagination flow (two-query distinct-id strategy), so the docs are now misleading.
### Issue Context
The join+pagination logic now triggers when `expressionMap.limit/offset` are set, and a new functional test validates `.leftJoinAndSelect(...).limit(1).getMany()` should return 1 root entity with all joined rows.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[1534-1560]
- src/query-builder/SelectQueryBuilder.ts[3586-3596]

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


Grey Divider

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

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Persistent review updated to latest commit a64b6ad

@gioboa
gioboa merged commit eacc2ca into typeorm:master Feb 14, 2026
38 checks passed
@gioboa
gioboa deleted the fix/3967 branch February 14, 2026 13:48
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
@cduff cduff mentioned this pull request May 10, 2026
1 of 18 tasks
@cduff

cduff commented May 10, 2026

Copy link
Copy Markdown
Contributor

@gioboa It looks like this change is causing a performance/behaviour regression with QueryBuilder limit()?

See #12445.

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I see.
In the this PR I added this comment:

When joins are present, a two-quer y distinct-id strategy is used

@cduff

cduff commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

I see. In the this PR I added this comment:

When joins are present, a two-quer y distinct-id strategy is used

Yes I saw that @gioboa. I'd say it's a regression in performance and behaviour though. It means it's no longer possible to do a performant offset/limit-style query using QueryBuilder (when joins are present). take/skip was already the documented approach for a "two-query distinct-id strategy" query.

@gioboa

gioboa commented May 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

I did a fast alignment with the core team, I'll try to create a PR to preserve this with a single query. I can't guarantee that it's possible, need to try. Thanks for the heads up though 👍

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Strange behavior when using limit with relations (joins)

5 participants