Skip to content

Conversation

EQuincerot
Copy link
Contributor

@EQuincerot EQuincerot commented Jun 12, 2025

Description of change

When getManyAndCount is called, stop execute the count query if it can be deduced from the
number of returned rows. This will increase performance by avoiding one round trip to the database. It would be especially useful when using pagination libraries such as https://github.com/ppetzold/nestjs-paginate and even more when the max results per page is rarely reached.

Example

const [entities, count] = await connection.manager
    .createQueryBuilder(Post, "post")
    .limit(10)
    .orderBy("post.id")
    .getManyAndCount()

Before this change, it triggers two queries:

SELECT * FROM post ORDER BY post.id LIMIT 10; -- returns 5 rows
SELECT count(*) FROM post; -- returns 5

But if the first query returns only 5 results, we know that the count will also be 5.

After this change, if the first query returns less rows than the limit, we don't trigger the count:

SELECT * FROM post ORDER BY post.id LIMIT 10; -- returns 5 rows
-- as rows < LIMIT we can skip the count query and set the count to 5

ℹ️ Note that this optimization also works when some filtering is done, as the filtering will be the same for the getMany as for the count.

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 unit tests validating the change
  • Documentation has been updated to reflect this change

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Improved query performance by optimizing when count queries are executed for certain database operations.
  • Tests
    • Added new tests to verify optimized count query behavior and ensure correct results are returned in various scenarios.
  • Chores
    • Introduced new entity and subscriber classes to support and monitor query testing.

Skip count query when it can be deduced from the
number of returned rows. This will avoid one round
trip and could be very helpful on pagination when the
limit is not reached.
Copy link

pkg-pr-new bot commented Jun 12, 2025

typeorm-sql-js-example

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

commit: 8b378e7

Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

The changes introduce a lazy count optimization in the SelectQueryBuilder's getManyAndCount method, allowing the count query to be skipped when possible. Supporting this, new entity classes Post and Comment, a query event subscriber, and a test suite are added to verify and monitor this behavior, ensuring correctness in scenarios involving limits, offsets, and joins.

Changes

File(s) Change Summary
src/query-builder/SelectQueryBuilder.ts Modified getManyAndCount to infer count from fetched entities when possible, skipping count query. Added private lazyCount method.
test/other-issues/lazy-count/entity/Post.ts Added Post entity with id, content, and one-to-many comments relation with cascade insert.
test/other-issues/lazy-count/entity/Comment.ts Added Comment entity with id, title, and many-to-one post relation.
test/other-issues/lazy-count/lazy-count.ts Added test suite verifying lazy count behavior on Post entity with various limits, offsets, and joins.
test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts Added AfterQuerySubscriber to record and manage executed queries for test verification.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite as Test Suite
    participant QueryBuilder as SelectQueryBuilder
    participant DB as Database
    participant Subscriber as AfterQuerySubscriber

    TestSuite->>QueryBuilder: getManyAndCount({ take/limit, skip/offset })
    QueryBuilder->>DB: SELECT entities
    DB-->>QueryBuilder: entities[]
    alt conditions allow lazy count
        QueryBuilder-->>TestSuite: [entities[], inferredCount]
    else
        QueryBuilder->>DB: SELECT COUNT(*)
        DB-->>QueryBuilder: count
        QueryBuilder-->>TestSuite: [entities[], count]
    end
    QueryBuilder-->>Subscriber: afterQuery event(s)
Loading

Poem

In the warren of queries, a shortcut we found,
When fetching is fewer, no count query’s bound.
With Posts and Comments, and a watcher so keen,
The code now is clever, efficient, and lean.
🐇✨
Lazy counts make this bunny hop with glee!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-23T17_45_25_650Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c64e3a and 8b378e7.

📒 Files selected for processing (1)
  • src/query-builder/SelectQueryBuilder.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/query-builder/SelectQueryBuilder.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts (1)

8-29: Strengthen typing & encapsulation of calledQueries.

calledQueries stores raw SQL strings, yet it’s typed as any[] and left public.
Tighten the contract and avoid accidental external mutation:

-    calledQueries: any[] = []
+    private calledQueries: string[] = []

No downstream code relies on direct field access (tests use the helper methods), so this should be non-breaking while improving safety.

src/query-builder/SelectQueryBuilder.ts (1)

1892-1899: Minor issues in cache-id handling & typo

  1. Typo: retreiveretrieve.
  2. this.expressionMap.cacheId = cacheId ? \${cacheId}-count` : cacheId ‑ WhencacheIdisundefined` the assignment is a no-op; consider skipping it entirely to avoid the extra write.
  3. The original cacheId is not restored after the count query; if the same builder instance is reused later it will carry the suffixed id.
- // Creates a new cacheId for the count query, or it will retreive the above query results
+ // Creates a new cacheId for the count query, or it will retrieve the previous query results
...
- this.expressionMap.cacheId = cacheId ? `${cacheId}-count` : cacheId
+ if (cacheId) {
+     this.expressionMap.cacheId = `${cacheId}-count`
+ }

Restore cacheId after executeCountQuery if the builder is intended to be reusable.

test/other-issues/lazy-count/lazy-count.ts (4)

29-34: Factor out test-data seeding to reduce repetition

The four for-loops that seed 2 – 5 Post rows are identical boilerplate. Extracting a small helper (e.g. await seedPosts(connection, 5)) keeps each test focused on the behaviour under scrutiny and makes future changes to the seed logic (different entity, additional fields, etc.) one-liner edits.

Also applies to: 58-63, 87-92, 116-121


36-38: Avoid brittle index-based access to the subscriber

connection.subscribers[0] silently breaks if another subscriber is registered first.
Prefer a type/instance lookup:

-const afterQuery = connection.subscribers[0] as AfterQuerySubscriber
+const afterQuery = connection.subscribers.find(
+    (s): s is AfterQuerySubscriber => s instanceof AfterQuerySubscriber,
+)!

This is safer and self-documenting.


50-52: Regex assertion may miss driver-specific COUNT syntax

The check /.?count/i assumes the raw SQL contains the literal word COUNT. Some drivers alias the aggregate (e.g. "COUNT"("*)""cnt") or wrap it in comments, causing false negatives/positives.
A stricter approach is to expose a boolean from AfterQuerySubscriber like wasCountExecuted instead of string-matching the SQL text.

Also applies to: 79-81, 108-110, 138-140


46-49: Inconsistent Chai styles (should vs expect)

Each assertion mixes the should interface (count.should.be.equal(...)) with the expect interface. While both work, sticking to one style per file avoids cognitive overhead and linter noise.

Also applies to: 75-78, 104-107, 134-137

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 42913b9 and 7800611.

📒 Files selected for processing (4)
  • src/query-builder/SelectQueryBuilder.ts (1 hunks)
  • test/other-issues/lazy-count/entity/Post.ts (1 hunks)
  • test/other-issues/lazy-count/lazy-count.ts (1 hunks)
  • test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts (1)
src/subscriber/event/QueryEvent.ts (1)
  • AfterQueryEvent (39-59)
src/query-builder/SelectQueryBuilder.ts (1)
src/entity-manager/EntityManager.ts (1)
  • count (1005-1017)
🔇 Additional comments (3)
test/other-issues/lazy-count/entity/Post.ts (1)

3-10: Looks good – minimal, portable entity definition.

The entity is concise and follows TypeORM conventions; no blocking issues spotted.

src/query-builder/SelectQueryBuilder.ts (1)

1880-1891: Edge-case: deduplication via joins can yield entities.length < take while more rows still exist

The shortcut assumes that if entities.length < take|limit (and no skip/offset) then the full result-set was fetched.
With joins TypeORM uses DISTINCT sub-queries to get entity IDs, but the final entities.length is calculated after hydration & duplicate elimination.

Example:

take = 10
DISTINCT sub-query picks 10 ids
JOIN duplicates inflate the result-set → 25 raw rows
Hydrator collapses them to, say, 8 unique entities

entities.length becomes 8 < take, the count query is skipped and 8 is returned, while at least 10 entities actually exist.

Please double-check entitiesAndRaw always contains exactly take|limit unique entities when more are available (incl. eager relations / complex joins).
If not, fallback to the explicit count query whenever joins are present or after comparing against the size of the DISTINCT id list instead of the hydrated entity list.

test/other-issues/lazy-count/lazy-count.ts (1)

40-45: Cross-dialect caution: .limit() is MySQL-only

QueryBuilder.limit() is translated only by MySQL drivers; for Postgres/SQLite/etc. the call is ignored. If the test-suite ever runs on those dialects, this test will misleadingly behave like the .take() tests. Consider sticking to .take() for portability or gating the test to MySQL connections.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
test/other-issues/lazy-count/entity/Post.ts (1)

17-21: Initialize or assert the comments collection

comments is declared without a definite-assignment assertion (!) or an initial value.
With strictPropertyInitialization enabled, this triggers TS2740; at runtime it may also be undefined, forcing callers to null-check. Two quick fixes:

-    comments: Comment[]
+    comments!: Comment[]            // 💡 simplest – assert it will be set
+
+    // Or give it a safe default:
+    // comments: Comment[] = []

Either option keeps the intent clear and avoids unnecessary undefined checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9eec89d and b85a488.

📒 Files selected for processing (5)
  • src/query-builder/SelectQueryBuilder.ts (2 hunks)
  • test/other-issues/lazy-count/entity/Comment.ts (1 hunks)
  • test/other-issues/lazy-count/entity/Post.ts (1 hunks)
  • test/other-issues/lazy-count/lazy-count.ts (1 hunks)
  • test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/other-issues/lazy-count/entity/Comment.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/other-issues/lazy-count/subscribers/AfterQuerySubscriber.ts
  • src/query-builder/SelectQueryBuilder.ts
  • test/other-issues/lazy-count/lazy-count.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
test/other-issues/lazy-count/entity/Post.ts (4)
test/other-issues/lazy-count/entity/Comment.ts (1)
  • Entity (9-23)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
src/decorator/relations/OneToMany.ts (1)
  • OneToMany (11-47)
🔇 Additional comments (1)
test/other-issues/lazy-count/entity/Post.ts (1)

9-16: Entity skeleton looks good

The basic entity wiring (primary key + simple column) is correct and consistent with the conventions used elsewhere in the test-suite.

@EQuincerot EQuincerot requested a review from alumni June 16, 2025 15:46
@gioboa
Copy link
Collaborator

gioboa commented Jun 20, 2025

Thanks for your amazing help @EQuincerot
Kudos for your first PR in this project 🎉

Copy link
Collaborator

@sgarner sgarner left a comment

Choose a reason for hiding this comment

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

Nice fix, thank you @EQuincerot

Just a few code improvements that could be made.

Copy link
Collaborator

@sgarner sgarner left a comment

Choose a reason for hiding this comment

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

One more tweak, otherwise looks good 👍

@EQuincerot EQuincerot requested a review from sgarner June 23, 2025 12:43
Copy link
Collaborator

@sgarner sgarner left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution @EQuincerot 💜

@sgarner sgarner merged commit 5904ac3 into typeorm:master Jun 23, 2025
58 checks passed
Copy link
Collaborator

@gioboa gioboa left a comment

Choose a reason for hiding this comment

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

Great improvement @EQuincerot thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants