Skip to content

revert: fix up limit with joins - #12478

Merged
gioboa merged 3 commits into
typeorm:masterfrom
gioboa:revert/11987
May 14, 2026
Merged

gioboa merged 3 commits into
typeorm:masterfrom
gioboa:revert/11987

Conversation

@gioboa

@gioboa gioboa commented May 13, 2026

Copy link
Copy Markdown
Collaborator

Close #12445

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)

🛡️ Security fixes: Do not submit security fixes as public PRs — the diff exposes the vulnerability. Use GitHub Security Advisories instead.

@gioboa gioboa changed the title revert: fix up limit with joins #11987 revert: fix up limit with joins (#11987) May 13, 2026
@gioboa gioboa changed the title revert: fix up limit with joins (#11987) revert: fix up limit with joins May 13, 2026
@pkg-pr-new

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

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

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

commit: e0040d2

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (3)

Grey Divider


Action required

1. 6-pagination.md misleads on joins 📘 Rule violation ⚙ Maintainability
Description
The pagination docs still recommend using limit/offset, but the updated
SelectQueryBuilder.limit()/.offset() JSDoc now warns that these may not behave as expected with
joins and recommends take/skip, creating inconsistent user guidance. Additionally, the newly
added NOTE text is awkwardly phrased and less precise than prior explanations, reducing clarity
and introducing style-inconsistent documentation noise.
Code

src/query-builder/SelectQueryBuilder.ts[R1484-1488]

   /**
    * Sets LIMIT - maximum number of rows to be selected.
-     * When joins are present, a two-query distinct-id strategy is used
-     * so that LIMIT applies to root entities rather than raw joined rows.
+     * NOTE that it may not work as you expect if you are using joins.
+     * If you want to implement pagination, and you are having join in your query,
+     * then use the take method instead.
Evidence
The documentation page explicitly instructs users to paginate with limit and offset, while the
updated JSDoc for SelectQueryBuilder.limit()/.offset() adds a join-related warning and points
users toward take/skip, demonstrating that user-facing guidance has changed in code comments
without corresponding alignment in the docs. The added JSDoc also includes a vague “NOTE” and
ungrammatical phrasing (e.g., “you are having join”), which supports the concern that lower-quality,
style-inconsistent text is being introduced into API documentation.

Rule 2: Docs updated for user-facing changes
Rule 4: Remove AI-generated noise
docs/docs/performance-optimization/6-pagination.md[5-13]
src/query-builder/SelectQueryBuilder.ts[1484-1502]

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

## Issue description
Align pagination guidance across the docs and JSDoc: the docs currently recommend `limit`/`offset` without caveats, while the `SelectQueryBuilder.limit()`/`.offset()` JSDoc warns that join usage may not behave as expected and recommends `take`/`skip`. Also revise the newly added JSDoc `NOTE` to be grammatically correct, precise about the behavior with joins, and consistent with the project’s documentation style.
## Issue Context
This is a user-facing documentation mismatch and quality issue: users reading the docs may implement pagination with `limit`/`offset` expecting root-entity pagination even when joins are involved, despite the API JSDoc warning otherwise. The JSDoc itself should avoid vague or awkward phrasing and clearly explain the limitation and recommended alternatives (`take`/`skip`) in a professional, consistent tone.
## Fix Focus Areas
- docs/docs/performance-optimization/6-pagination.md[5-13]
- src/query-builder/SelectQueryBuilder.ts[1484-1502]

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


2. Mixed pagination inconsistent 🐞 Bug ≡ Correctness
Description
In SelectQueryBuilder.executeEntitiesAndRawResults, the join-pagination path paginates the outer
DISTINCT query using only skip/take, but does not clear limit/offset from the inner/second query
clones, so queries like .skip(10).limit(5) (or .take(5).offset(10)) produce incorrect paging and can
throw OffsetWithoutLimitNotSupportedError on MySQL-family when the outer query receives OFFSET
without LIMIT.
Code

src/query-builder/SelectQueryBuilder.ts[R3458-3462]

           const originalQuery = this.clone()

-            // clear limit/offset from the inner query since pagination is handled by the outer distinct query
-            originalQuery.expressionMap.limit = undefined
-            originalQuery.expressionMap.offset = undefined
-
           // preserve original timeTravel value since we set it to "false" in subquery
           const originalQueryTimeTravel =
               originalQuery.expressionMap.timeTravel
Evidence
The join-pagination DISTINCT query now uses only skip/take, but SQL generation still prefers
limit/offset when present; because limit/offset are not cleared on the cloned inner/second queries,
mixed usage leads to mismatched pagination behavior between inner and outer queries (including
OFFSET-without-LIMIT on MySQL-family).

src/query-builder/SelectQueryBuilder.ts[3415-3485]
src/query-builder/SelectQueryBuilder.ts[3538-3545]
src/query-builder/SelectQueryBuilder.ts[2614-2670]
src/query-builder/SelectQueryBuilder.ts[1484-1528]

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

## Issue description
`executeEntitiesAndRawResults` enters the two-query DISTINCT-id pagination flow when joins exist and `skip`/`take` are set. After this PR, the pagination query builder uses only `skip`/`take` (`.offset(this.expressionMap.skip).limit(this.expressionMap.take)`), while the inner subquery is built from `originalQuery = this.clone()` with **no clearing** of `expressionMap.limit/offset`. Since SQL generation prefers `limit/offset` when they are set, mixing APIs (e.g., `.skip(10).limit(5)` or `.take(5).offset(10)`) leads to:
- inner subquery being constrained by `limit/offset` (joined-row semantics)
- outer DISTINCT pagination ignoring them (skip/take only), potentially emitting OFFSET without LIMIT on MySQL-family
### Issue Context
TypeORM exposes `limit/offset` and `take/skip` simultaneously and does not enforce mutual exclusivity, so this state can occur in real usage.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3415-3545]
- src/query-builder/SelectQueryBuilder.ts[2614-2693]
- src/query-builder/SelectQueryBuilder.ts[1484-1528]
### Suggested fix
In the join-pagination block:
1. Compute pagination values consistently, e.g.:
 - `const offset = this.expressionMap.skip ?? this.expressionMap.offset`
 - `const limit = this.expressionMap.take ?? this.expressionMap.limit`
2. Apply those computed values to the pagination DISTINCT query (`.offset(offset).limit(limit)`).
3. Ensure `originalQuery` (and the second query used to load raw results) does not carry `expressionMap.limit/offset` into the inner joined query by explicitly setting them to `undefined` before calling `getQuery()` / `loadRawResults()`.
This keeps the revert behavior for pure limit/offset+joins (since the block still only triggers on skip/take), while making mixed usage deterministic and preventing the inner query from being unintentionally limited.

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


3. Double-applied limit/offset 🐞 Bug ≡ Correctness
Description
In executeEntitiesAndRawResults(), the skip/take+joins two-query pagination path no longer clears
expressionMap.limit/offset on the inner subquery or the second data-load query, so using
.limit()/.offset() together with .take()/.skip() can apply limiting twice and return incomplete root
entities/relations. This happens because createLimitOffsetExpression() prioritizes
expressionMap.limit/offset whenever they are set, even when joins are present.
Code

src/query-builder/SelectQueryBuilder.ts[R3571-3576]

+                rawResults = await this.clone()
                  .mergeExpressionMap({
                      extraAppendedAndWhereCondition: condition,
                  })
                  .setParameters(parameters)
-                secondQuery.expressionMap.limit = undefined
-                secondQuery.expressionMap.offset = undefined
-                rawResults = await secondQuery.loadRawResults(queryRunner)
+                    .loadRawResults(queryRunner)
Evidence
The pagination branch builds a subquery from originalQuery.getQuery() and then runs a second query
from this.clone() without clearing limit/offset. Since createLimitOffsetExpression() uses
expressionMap.offset/limit whenever set (and does not fall back to skip/take when joins exist),
any .limit()/.offset() set on the main builder will influence both queries and can truncate
results.

src/query-builder/SelectQueryBuilder.ts[3447-3577]
src/query-builder/SelectQueryBuilder.ts[2643-2658]
src/query-builder/SelectQueryBuilder.ts[1484-1524]

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 join-pagination is active (two-query distinct-id strategy), `.limit()` / `.offset()` must not affect the inner subquery nor the second "load by ids" query. The PR removed the explicit clearing of `expressionMap.limit` / `expressionMap.offset`, so if callers set both (`take/skip` for pagination + `limit/offset` via shared builder code), limits/offsets can be applied twice and truncate results.
### Issue Context
`createLimitOffsetExpression()` uses `expressionMap.offset/limit` whenever they exist, and only maps `skip/take` to `offset/limit` when there are *no joins*. Therefore, in the join-pagination branch, any user-provided `limit/offset` will leak into both the inner subquery (`originalQuery.getQuery()`) and the second query unless explicitly cleared.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3490-3512]
- src/query-builder/SelectQueryBuilder.ts[3571-3576]
Suggested change: in the join-pagination branch, ensure `originalQuery` and the second-query clone call `.offset(undefined).limit(undefined)` (or directly clear `expressionMap.offset/limit`) before generating SQL / loading raw results.

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



Remediation recommended

4. Removed join limit functional test 📘 Rule violation ☼ Reliability
Description
The PR changes join pagination behavior to only trigger the two-query strategy for skip/take,
while removing the functional test that validated limit with left joins and not adding a
replacement test in test/functional. This weakens functional coverage for an issue-related
behavior change.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[L1685-1721]

-    it("should return correct number of results when limit is used with left joins", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                const manager = dataSource.manager
-
-                for (let i = 1; i <= 7; i++) {
-                    const user = new User()
-                    user.name = `User ${i}`
-                    await manager.save(user)
-
-                    for (let j = 1; j <= 2; j++) {
-                        const photo = new Photo()
-                        photo.name = `Photo ${i}-${j}`
-                        photo.user = user
-                        await manager.save(photo)
-                    }
-                }
-
-                const qb = manager
-                    .createQueryBuilder(User, "user")
-                    .leftJoinAndSelect("user.photos", "photo")
-                    .orderBy("user.id")
-                    .limit(5)
-
-                const users = await qb.getMany()
-                expect(users).to.have.lengthOf(5)
-                users.forEach((user) => {
-                    expect(user.photos).to.have.lengthOf(2)
-                })
-
-                const rows = await qb.execute()
-                const uniqueIds = new Set(
-                    rows.map((row: { user_id: string }) => row.user_id),
-                )
-                expect(uniqueIds.size).to.equal(3)
-            }),
-        ))
Evidence
Rule 3 expects issue fixes to be validated via the functional test suite. The implementation now
only applies the special pagination path when skip/take is used with joins, but the join test
file contains no limit coverage, indicating the removed functional test was not replaced with an
updated functional test for the changed behavior.

Rule 3: Prefer functional tests over per-issue tests
src/query-builder/SelectQueryBuilder.ts[3415-3422]
test/functional/query-builder/join/query-builder-joins.test.ts[1-15]
test/functional/query-builder/join/query-builder-joins.test.ts[1661-1683]

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

## Issue description
A functional test covering `limit` with joins was removed, while the pagination-with-joins implementation was also changed (now gated on `skip`/`take`). There is no updated functional test asserting the intended behavior.
## Issue Context
Per the compliance requirement, issue-related behavior changes should be covered in the functional test suite.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3415-3480]
- test/functional/query-builder/join/query-builder-joins.test.ts[1-1683]

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


5. limit() JSDoc awkward NOTE 📘 Rule violation ⚙ Maintainability
Description
The new JSDoc NOTE text added to SelectQueryBuilder.limit() and SelectQueryBuilder.offset()
contains awkward/unnatural phrasing (e.g., you are having join) and an inconsistent style compared
to surrounding documentation. This introduces AI-like comment noise and reduces documentation
clarity for users.
Code

src/query-builder/SelectQueryBuilder.ts[R1486-1488]

+     * NOTE that it may not work as you expect if you are using joins.
+     * If you want to implement pagination, and you are having join in your query,
+     * then use the take method instead.
Evidence
PR Compliance ID 4 forbids introducing AI-like comments or inconsistent documentation style. The
cited additions in the limit() and offset() JSDoc blocks include an all-caps NOTE and awkward
phrasing such as you are having join, which directly matches the rule’s failure criteria for
unnatural, generated-sounding text and inconsistent style.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[1486-1488]
src/query-builder/SelectQueryBuilder.ts[1507-1509]

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()` and `SelectQueryBuilder.offset()` have newly-added NOTE text in their JSDoc that uses awkward/unnatural phrasing and inconsistent style, violating the requirement to avoid AI-generated/comment noise and reducing documentation clarity.
## Issue Context
The added NOTE lines read like generated text (e.g., `you are having join`) and use an inconsistent all-caps NOTE format; they should be rewritten (or removed if unnecessary) to match the project’s typical documentation tone, grammar, and style.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[1486-1488]
- src/query-builder/SelectQueryBuilder.ts[1507-1509]

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


6. Removed join-limit regression test 🐞 Bug ⚙ Maintainability
Description
The PR deletes the functional test (and its supporting Photo entity) that asserted correct
root-entity results when using .limit() with left joins, reducing CI coverage for a historically
fragile query-builder behavior. This makes it easier for future regressions around
joins+limit/offset to ship unnoticed.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[L1685-1721]

-    it("should return correct number of results when limit is used with left joins", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                const manager = dataSource.manager
-
-                for (let i = 1; i <= 7; i++) {
-                    const user = new User()
-                    user.name = `User ${i}`
-                    await manager.save(user)
-
-                    for (let j = 1; j <= 2; j++) {
-                        const photo = new Photo()
-                        photo.name = `Photo ${i}-${j}`
-                        photo.user = user
-                        await manager.save(photo)
-                    }
-                }
-
-                const qb = manager
-                    .createQueryBuilder(User, "user")
-                    .leftJoinAndSelect("user.photos", "photo")
-                    .orderBy("user.id")
-                    .limit(5)
-
-                const users = await qb.getMany()
-                expect(users).to.have.lengthOf(5)
-                users.forEach((user) => {
-                    expect(user.photos).to.have.lengthOf(2)
-                })
-
-                const rows = await qb.execute()
-                const uniqueIds = new Set(
-                    rows.map((row: { user_id: string }) => row.user_id),
-                )
-                expect(uniqueIds.size).to.equal(3)
-            }),
-        ))
Evidence
The join test file no longer imports Photo and now ends without any assertion about .limit()
behavior with joins, while .limit() still exists in the query builder API.

test/functional/query-builder/join/query-builder-joins.test.ts[7-16]
test/functional/query-builder/join/query-builder-joins.test.ts[1661-1683]
src/query-builder/SelectQueryBuilder.ts[1484-1503]

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

## Issue description
A targeted regression test covering `limit` with joins was removed. Even if behavior is being reverted/changed, we should keep an explicit test that asserts the *intended* behavior for joins+limiting (e.g., enforce that pagination with joins must use `take/skip`, or add a test that ensures `take/skip` pagination ignores `limit/offset` when both are set).
### Issue Context
`SelectQueryBuilder.limit()/offset()` remain public APIs and are documented as potentially surprising with joins; without any test coverage, regressions in this area become hard to detect.
### Fix Focus Areas
- test/functional/query-builder/join/query-builder-joins.test.ts[1-1683]
Suggested change: add a new test case (and minimal entities if needed) that codifies the expected behavior after this revert (either expected failure/behavioral limitation of `.limit()` with joins, or correct behavior when using `take/skip`).

ⓘ 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.

Previous review results

Review updated until commit e0040d2

Results up to commit 8616e42


🐞 Bugs (3) 📘 Rule violations (3)


Action required
1. 6-pagination.md misleads on joins 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The pagination docs still recommend using limit/offset, but the updated
SelectQueryBuilder.limit()/.offset() JSDoc now warns that these may not behave as expected with
joins and recommends take/skip, creating inconsistent user guidance. Additionally, the newly
added NOTE text is awkwardly phrased and less precise than prior explanations, reducing clarity
and introducing style-inconsistent documentation noise.
Code

src/query-builder/SelectQueryBuilder.ts[R1484-1488]

    /**
     * Sets LIMIT - maximum number of rows to be selected.
-     * When joins are present, a two-query distinct-id strategy is used
-     * so that LIMIT applies to root entities rather than raw joined rows.
+     * NOTE that it may not work as you expect if you are using joins.
+     * If you want to implement pagination, and you are having join in your query,
+     * then use the take method instead.
Evidence
The documentation page explicitly instructs users to paginate with limit and offset, while the
updated JSDoc for SelectQueryBuilder.limit()/.offset() adds a join-related warning and points
users toward take/skip, demonstrating that user-facing guidance has changed in code comments
without corresponding alignment in the docs. The added JSDoc also includes a vague “NOTE” and
ungrammatical phrasing (e.g., “you are having join”), which supports the concern that lower-quality,
style-inconsistent text is being introduced into API documentation.

Rule 2: Docs updated for user-facing changes
Rule 4: Remove AI-generated noise
docs/docs/performance-optimization/6-pagination.md[5-13]
src/query-builder/SelectQueryBuilder.ts[1484-1502]

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

## Issue description
Align pagination guidance across the docs and JSDoc: the docs currently recommend `limit`/`offset` without caveats, while the `SelectQueryBuilder.limit()`/`.offset()` JSDoc warns that join usage may not behave as expected and recommends `take`/`skip`. Also revise the newly added JSDoc `NOTE` to be grammatically correct, precise about the behavior with joins, and consistent with the project’s documentation style.

## Issue Context
This is a user-facing documentation mismatch and quality issue: users reading the docs may implement pagination with `limit`/`offset` expecting root-entity pagination even when joins are involved, despite the API JSDoc warning otherwise. The JSDoc itself should avoid vague or awkward phrasing and clearly explain the limitation and recommended alternatives (`take`/`skip`) in a professional, consistent tone.

## Fix Focus Areas
- docs/docs/performance-optimization/6-pagination.md[5-13]
- src/query-builder/SelectQueryBuilder.ts[1484-1502]

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


2. Mixed pagination inconsistent 🐞 Bug ≡ Correctness ⭐ New
Description
In SelectQueryBuilder.executeEntitiesAndRawResults, the join-pagination path paginates the outer
DISTINCT query using only skip/take, but does not clear limit/offset from the inner/second query
clones, so queries like .skip(10).limit(5) (or .take(5).offset(10)) produce incorrect paging and can
throw OffsetWithoutLimitNotSupportedError on MySQL-family when the outer query receives OFFSET
without LIMIT.
Code

src/query-builder/SelectQueryBuilder.ts[R3458-3462]

            const originalQuery = this.clone()

-            // clear limit/offset from the inner query since pagination is handled by the outer distinct query
-            originalQuery.expressionMap.limit = undefined
-            originalQuery.expressionMap.offset = undefined
-
            // preserve original timeTravel value since we set it to "false" in subquery
            const originalQueryTimeTravel =
                originalQuery.expressionMap.timeTravel
Evidence
The join-pagination DISTINCT query now uses only skip/take, but SQL generation still prefers
limit/offset when present; because limit/offset are not cleared on the cloned inner/second queries,
mixed usage leads to mismatched pagination behavior between inner and outer queries (including
OFFSET-without-LIMIT on MySQL-family).

src/query-builder/SelectQueryBuilder.ts[3415-3485]
src/query-builder/SelectQueryBuilder.ts[3538-3545]
src/query-builder/SelectQueryBuilder.ts[2614-2670]
src/query-builder/SelectQueryBuilder.ts[1484-1528]

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

### Issue description
`executeEntitiesAndRawResults` enters the two-query DISTINCT-id pagination flow when joins exist and `skip`/`take` are set. After this PR, the pagination query builder uses only `skip`/`take` (`.offset(this.expressionMap.skip).limit(this.expressionMap.take)`), while the inner subquery is built from `originalQuery = this.clone()` with **no clearing** of `expressionMap.limit/offset`. Since SQL generation prefers `limit/offset` when they are set, mixing APIs (e.g., `.skip(10).limit(5)` or `.take(5).offset(10)`) leads to:
- inner subquery being constrained by `limit/offset` (joined-row semantics)
- outer DISTINCT pagination ignoring them (skip/take only), potentially emitting OFFSET without LIMIT on MySQL-family

### Issue Context
TypeORM exposes `limit/offset` and `take/skip` simultaneously and does not enforce mutual exclusivity, so this state can occur in real usage.

### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3415-3545]
- src/query-builder/SelectQueryBuilder.ts[2614-2693]
- src/query-builder/SelectQueryBuilder.ts[1484-1528]

### Suggested fix
In the join-pagination block:
1. Compute pagination values consistently, e.g.:
  - `const offset = this.expressionMap.skip ?? this.expressionMap.offset`
  - `const limit = this.expressionMap.take ?? this.expressionMap.limit`
2. Apply those computed values to the pagination DISTINCT query (`.offset(offset).limit(limit)`).
3. Ensure `originalQuery` (and the second query used to load raw results) does not carry `expressionMap.limit/offset` into the inner joined query by explicitly setting them to `undefined` before calling `getQuery()` / `loadRawResults()`.

This keeps the revert behavior for pure limit/offset+joins (since the block still only triggers on skip/take), while making mixed usage deterministic and preventing the inner query from being unintentionally limited.

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


3. Double-applied limit/offset 🐞 Bug ≡ Correctness
Description
In executeEntitiesAndRawResults(), the skip/take+joins two-query pagination path no longer clears
expressionMap.limit/offset on the inner subquery or the second data-load query, so using
.limit()/.offset() together with .take()/.skip() can apply limiting twice and return incomplete root
entities/relations. This happens because createLimitOffsetExpression() prioritizes
expressionMap.limit/offset whenever they are set, even when joins are present.
Code

src/query-builder/SelectQueryBuilder.ts[R3571-3576]

+                rawResults = await this.clone()
                   .mergeExpressionMap({
                       extraAppendedAndWhereCondition: condition,
                   })
                   .setParameters(parameters)
-                secondQuery.expressionMap.limit = undefined
-                secondQuery.expressionMap.offset = undefined
-                rawResults = await secondQuery.loadRawResults(queryRunner)
+                    .loadRawResults(queryRunner)
Evidence
The pagination branch builds a subquery from originalQuery.getQuery() and then runs a second query
from this.clone() without clearing limit/offset. Since createLimitOffsetExpression() uses
expressionMap.offset/limit whenever set (and does not fall back to skip/take when joins exist),
any .limit()/.offset() set on the main builder will influence both queries and can truncate
results.

src/query-builder/SelectQueryBuilder.ts[3447-3577]
src/query-builder/SelectQueryBuilder.ts[2643-2658]
src/query-builder/SelectQueryBuilder.ts[1484-1524]

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 join-pagination is active (two-query distinct-id strategy), `.limit()` / `.offset()` must not affect the inner subquery nor the second "load by ids" query. The PR removed the explicit clearing of `expressionMap.limit` / `expressionMap.offset`, so if callers set both (`take/skip` for pagination + `limit/offset` via shared builder code), limits/offsets can be applied twice and truncate results.
### Issue Context
`createLimitOffsetExpression()` uses `expressionMap.offset/limit` whenever they exist, and only maps `skip/take` to `offset/limit` when there are *no joins*. Therefore, in the join-pagination branch, any user-provided `limit/offset` will leak into both the inner subquery (`originalQuery.getQuery()`) and the second query unless explicitly cleared.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3490-3512]
- src/query-builder/SelectQueryBuilder.ts[3571-3576]
Suggested change: in the join-pagination branch, ensure `originalQuery` and the second-query clone call `.offset(undefined).limit(undefined)` (or directly clear `expressionMap.offset/limit`) before generating SQL / loading raw results.

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



Remediation recommended
4. Removed join limit functional test 📘 Rule violation ☼ Reliability ⭐ New
Description
The PR changes join pagination behavior to only trigger the two-query strategy for skip/take,
while removing the functional test that validated limit with left joins and not adding a
replacement test in test/functional. This weakens functional coverage for an issue-related
behavior change.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[L1685-1721]

-    it("should return correct number of results when limit is used with left joins", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                const manager = dataSource.manager
-
-                for (let i = 1; i <= 7; i++) {
-                    const user = new User()
-                    user.name = `User ${i}`
-                    await manager.save(user)
-
-                    for (let j = 1; j <= 2; j++) {
-                        const photo = new Photo()
-                        photo.name = `Photo ${i}-${j}`
-                        photo.user = user
-                        await manager.save(photo)
-                    }
-                }
-
-                const qb = manager
-                    .createQueryBuilder(User, "user")
-                    .leftJoinAndSelect("user.photos", "photo")
-                    .orderBy("user.id")
-                    .limit(5)
-
-                const users = await qb.getMany()
-                expect(users).to.have.lengthOf(5)
-                users.forEach((user) => {
-                    expect(user.photos).to.have.lengthOf(2)
-                })
-
-                const rows = await qb.execute()
-                const uniqueIds = new Set(
-                    rows.map((row: { user_id: string }) => row.user_id),
-                )
-                expect(uniqueIds.size).to.equal(3)
-            }),
-        ))
Evidence
Rule 3 expects issue fixes to be validated via the functional test suite. The implementation now
only applies the special pagination path when skip/take is used with joins, but the join test
file contains no limit coverage, indicating the removed functional test was not replaced with an
updated functional test for the changed behavior.

Rule 3: Prefer functional tests over per-issue tests
src/query-builder/SelectQueryBuilder.ts[3415-3422]
test/functional/query-builder/join/query-builder-joins.test.ts[1-15]
test/functional/query-builder/join/query-builder-joins.test.ts[1661-1683]

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

## Issue description
A functional test covering `limit` with joins was removed, while the pagination-with-joins implementation was also changed (now gated on `skip`/`take`). There is no updated functional test asserting the intended behavior.

## Issue Context
Per the compliance requirement, issue-related behavior changes should be covered in the functional test suite.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3415-3480]
- test/functional/query-builder/join/query-builder-joins.test.ts[1-1683]

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


5. limit() JSDoc awkward NOTE 📘 Rule violation ⚙ Maintainability
Description
The new JSDoc NOTE text added to SelectQueryBuilder.limit() and SelectQueryBuilder.offset()
contains awkward/unnatural phrasing (e.g., you are having join) and an inconsistent style compared
to surrounding documentation. This introduces AI-like comment noise and reduces documentation
clarity for users.
Code

src/query-builder/SelectQueryBuilder.ts[R1486-1488]

+     * NOTE that it may not work as you expect if you are using joins.
+     * If you want to implement pagination, and you are having join in your query,
+     * then use the take method instead.
Evidence
PR Compliance ID 4 forbids introducing AI-like comments or inconsistent documentation style. The
cited additions in the limit() and offset() JSDoc blocks include an all-caps NOTE and awkward
phrasing such as you are having join, which directly matches the rule’s failure criteria for
unnatural, generated-sounding text and inconsistent style.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[1486-1488]
src/query-builder/SelectQueryBuilder.ts[1507-1509]

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()` and `SelectQueryBuilder.offset()` have newly-added NOTE text in their JSDoc that uses awkward/unnatural phrasing and inconsistent style, violating the requirement to avoid AI-generated/comment noise and reducing documentation clarity.
## Issue Context
The added NOTE lines read like generated text (e.g., `you are having join`) and use an inconsistent all-caps NOTE format; they should be rewritten (or removed if unnecessary) to match the project’s typical documentation tone, grammar, and style.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[1486-1488]
- src/query-builder/SelectQueryBuilder.ts[1507-1509]

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


6. Removed join-limit regression test 🐞 Bug ⚙ Maintainability
Description
The PR deletes the functional test (and its supporting Photo entity) that asserted correct
root-entity results when using .limit() with left joins, reducing CI coverage for a historically
fragile query-builder behavior. This makes it easier for future regressions around
joins+limit/offset to ship unnoticed.
Code

test/functional/query-builder/join/query-builder-joins.test.ts[L1685-1721]

-    it("should return correct number of results when limit is used with left joins", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                const manager = dataSource.manager
-
-                for (let i = 1; i <= 7; i++) {
-                    const user = new User()
-                    user.name = `User ${i}`
-                    await manager.save(user)
-
-                    for (let j = 1; j <= 2; j++) {
-                        const photo = new Photo()
-                        photo.name = `Photo ${i}-${j}`
-                        photo.user = user
-                        await manager.save(photo)
-                    }
-                }
-
-                const qb = manager
-                    .createQueryBuilder(User, "user")
-                    .leftJoinAndSelect("user.photos", "photo")
-                    .orderBy("user.id")
-                    .limit(5)
-
-                const users = await qb.getMany()
-                expect(users).to.have.lengthOf(5)
-                users.forEach((user) => {
-                    expect(user.photos).to.have.lengthOf(2)
-                })
-
-                const rows = await qb.execute()
-                const uniqueIds = new Set(
-                    rows.map((row: { user_id: string }) => row.user_id),
-                )
-                expect(uniqueIds.size).to.equal(3)
-            }),
-        ))
Evidence
The join test file no longer imports Photo and now ends without any assertion about .limit()
behavior with joins, while .limit() still exists in the query builder API.

test/functional/query-builder/join/query-builder-joins.test.ts[7-16]
test/functional/query-builder/join/query-builder-joins.test.ts[1661-1683]
src/query-builder/SelectQueryBuilder.ts[1484-1503]

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

## Issue description
A targeted regression test covering `limit` with joins was removed. Even if behavior is being reverted/changed, we should keep an explicit test that asserts the *intended* behavior for joins+limiting (e.g., enforce that pagination with joins must use `take/skip`, or add a test that ensures `take/skip` pagination ignores `limit/offset` when both are set).
### Issue Context
`SelectQueryBuilder.limit()/offset()` remain public APIs and are documented as potentially surprising with joins; without any test coverage, regressions in this area become hard to detect.
### Fix Focus Areas
- test/functional/query-builder/join/query-builder-joins.test.ts[1-1683]
Suggested change: add a new test case (and minimal entities if needed) that codifies the expected behavior after this revert (either expected failure/behavioral limitation of `.limit()` with joins, or correct behavior when using `take/skip`).

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


Qodo Logo

@gioboa
gioboa requested review from Cprakhar and alumni May 13, 2026 13:53

@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.

This commit is reverting exactly #11987

@gioboa

gioboa commented May 13, 2026

Copy link
Copy Markdown
Collaborator Author

@cduff can you check this please? I reverted the changes in this PR.

@cduff

cduff commented May 14, 2026

Copy link
Copy Markdown
Contributor

@cduff can you check this please? I reverted the changes in this PR.

Thanks for your work on this @gioboa!

Looks good! I agree a revert of #11987 makes sense.

@gioboa
gioboa merged commit 62948a3 into typeorm:master May 14, 2026
46 checks passed
@gioboa
gioboa deleted the revert/11987 branch May 14, 2026 08:07
@github-actions github-actions Bot added this to the 1.0 milestone May 14, 2026
@gioboa gioboa added the backport This fix should be backported to a previous version label May 14, 2026
@alumni alumni removed the backport This fix should be backported to a previous version label May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

.limit() performance regression in v0.3.29

4 participants