Skip to content

feat: support distinct count - #11965

Merged
smith-xyz merged 15 commits into
typeorm:masterfrom
Cprakhar:feat/count-with-distinct
Jun 25, 2026
Merged

smith-xyz merged 15 commits into
typeorm:masterfrom
Cprakhar:feat/count-with-distinct

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Feb 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1186

Description of change

  • Added distinct-aware count for find-options select. If select is present, count method uses selected columns for distinct counting. If no select, old primary-column count path unchanged.
  • For selected relation columns for distinct counting, the relations option in the find-options needs to be there.
  • relationLoadStrategy: query doesn't make sense for count, as it fires separate queries (no-op).
  • Spatial types for mysql, postgres don't need hydration casting, but mssql types do need .toString().
  • JSONB/JSON for SQLite doesn't need hydration casting for counting.
@Entity()
export class Post {
  @PrimaryColumn()
  id: number

  @Column()
  name: string
}

// 1. name: "Bears"
// 2. name: "Bears"
// 3. name: "Dog"

const count = repo.count({ select: { name: true } })
// SELECT COUNT(DISTINCT("post"."name")) AS "cnt" from "post" "post"
console.log(count) // (2)

Pull-Request Checklist

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

@pkg-pr-new

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

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

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

commit: d69e5b6

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Spanner Category inserts fail 🐞 Bug ☼ Reliability
Description
The new distinct-count test inserts Category rows without an id, but Category uses
@PrimaryGeneratedColumn() (default increment). On Spanner, TypeORM includes increment-generated
columns in INSERTs and renders missing values as NULL, so these inserts can violate the NOT NULL
primary key constraint and fail the test on Spanner connections.
Code

test/functional/repository/find-methods/repostiory-find-methods.test.ts[R138-147]

+        it("should support distinct count when select is provided", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    const repository = dataSource.getRepository(Category)
+
+                    await repository.save([
+                        { name: "Bears" },
+                        { name: "Bears" },
+                        { name: "Cats" },
+                    ])
Evidence
The test inserts Category rows without ids, while @PrimaryGeneratedColumn() defaults to
increment. TypeORM’s insert builder explicitly does not skip increment-generated columns for
Spanner, and when a value is undefined and no default exists it emits NULL. Spanner’s DDL builder
doesn’t add any auto-increment/generation clause for such columns, so a NULL id insert can violate
the NOT NULL PK constraint.

test/functional/repository/find-methods/repostiory-find-methods.test.ts[138-147]
test/functional/repository/find-methods/entity/Category.ts[5-11]
src/decorator/columns/PrimaryGeneratedColumn.ts[83-101]
src/decorator/columns/PrimaryGeneratedColumn.ts[126-131]
src/query-builder/InsertQueryBuilder.ts[774-821]
src/query-builder/InsertQueryBuilder.ts[1325-1344]
src/driver/spanner/SpannerQueryRunner.ts[2508-2519]
ormconfig.sample.json[113-122]
test/utils/test-utils.ts[233-249]

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 `should support distinct count when select is provided` saves `Category` entities without setting `id`, while `Category.id` is declared with `@PrimaryGeneratedColumn()` (default strategy: `increment`). For the Spanner driver, generated `increment` columns are not omitted from INSERTs, so the INSERT statement will include `id` and bind it as `NULL` when not provided, which can fail with a NOT NULL primary key violation.
### Issue Context
This is a cross-driver functional test suite that can run against Spanner in the default driver set. Spanner’s query runner doesn’t generate auto-increment DDL for `increment` PKs, and the insert builder doesn’t skip increment-generated columns for Spanner.
### Fix Focus Areas
- test/functional/repository/find-methods/entity/Category.ts[1-12]
- test/functional/repository/find-methods/repostiory-find-methods.test.ts[138-161]
### Suggested fix
Pick one:
1) Make `Category.id` a manual PK (`@PrimaryColumn()`) and update the test inserts to provide explicit ids.
2) Keep `@PrimaryGeneratedColumn()` but update the test to insert ids explicitly (e.g. `{ id: 1, name: "Bears" }`) so it works on Spanner.
3) If the intent is to specifically test generated PK behavior, gate/disable this test for Spanner explicitly (least preferred since the feature under test is distinct counting, not PK generation).

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


2. Unterminated count SQL string 🐞 Bug ≡ Correctness
Description
computeDistinctCountExpression returns a malformed string literal in the generic fallback branch,
mixing a template-literal opener (backtick) with a double-quote terminator. This should cause a
TypeScript parse/compile error and block builds for any consumer of SelectQueryBuilder.
Code

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

Evidence
The return statement begins with a backtick (template literal) but ends with a double quote, leaving
the template literal unclosed and producing invalid TypeScript syntax.

src/query-builder/SelectQueryBuilder.ts[3107-3115]

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

## Issue description
`computeDistinctCountExpression()` has an unterminated string literal in the generic fallback return statement. The expression starts with a template string backtick but ends with a double quote, which makes the TypeScript file fail to parse/compile.
### Issue Context
This is in the fallback distinct-count branch used for drivers that don’t support multi-column `COUNT(DISTINCT ...)` natively.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3107-3115]
### Suggested fix
Change the return value to a properly delimited normal string (consistent with the other branches), e.g.:

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


3. Query strategy adds joins 🐞 Bug ☼ Reliability
Description
With relationLoadStrategy="query" and a relation field selected, buildRelations now both registers
the relation for separate-query loading and also pushes a JOIN into the main query, causing
redundant relation loading. This defeats the query strategy’s “no-join” behavior and can reintroduce
row-multiplication issues in the main SQL.
Code

src/query-builder/SelectQueryBuilder.ts[R4056-4078]

Evidence
SelectQueryBuilder.buildRelations calls concatRelationMetadata() for "query" strategy but still adds
a join when a relation selection exists, meaning the main query will JOIN the relation. Separately,
executeEntitiesAndRawResults still performs relation loading via separate queries when
relationLoadStrategy === "query", so the same relation can be fetched twice. This diverges from the
established "query" strategy behavior in FindOptionsUtils (which does not join under "query"), and
from docs that describe "query" as loading relations via separate queries instead of JOINs.

src/query-builder/SelectQueryBuilder.ts[4011-4087]
src/query-builder/SelectQueryBuilder.ts[3256-3287]
src/query-builder/SelectQueryBuilder.ts[3638-3674]
src/find-options/FindOptionsUtils.ts[245-258]
docs/docs/relations/5-eager-and-lazy-relations.md[69-74]

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 `relationLoadStrategy: "query"` is used, `buildRelations` currently both (a) registers the relation for separate-query loading via `concatRelationMetadata` and (b) conditionally adds a JOIN when `relationSelection` exists. This can lead to redundant relation loading (JOIN + separate query) and undermines the core purpose of the query strategy.
### Issue Context
The JOIN seems to be introduced to support distinct counting over selected relation columns. That requirement is specific to the `count()` path, but the current change impacts all find flows that use `applyFindOptions`.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4011-4087]
- src/query-builder/SelectQueryBuilder.ts[3638-3729]
- src/find-options/FindOptionsUtils.ts[245-258]
### Suggested direction
- Keep the "query" strategy behavior consistent: do **not** add JOINs in `buildRelations` when `relationLoadStrategy === "query"`.
- If JOINs are required only for the *count distinct* feature, scope them to the count execution path (e.g., in `executeCountQuery()` via a cloned builder or a count-specific flag), or ensure that when a JOIN is intentionally added under query strategy, the relation is **not** registered in `relationMetadatas` to avoid double-loading.

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


View more (7)
4. Query strategy skips relations 🐞 Bug ≡ Correctness
Description
When relationLoadStrategy is "query", relation selections from findOptions.select are never
converted into join selects, so computeSelectedColumnExpressions() can’t include relation columns
and count() won’t count distinct on the requested relation fields. This yields incorrect counts
for calls like `count({ select: { rel: { col: true } }, relations: { rel: true },
relationLoadStrategy: "query" })`.
Code

src/query-builder/SelectQueryBuilder.ts[R3044-3052]

Evidence
computeCountExpression() only switches to distinct counting based on expressions returned by
computeSelectedColumnExpressions(), which derives its column list exclusively from
expressionMap.selects. Relation field selects are only added via buildRelations() ->
buildSelect() when the relation load strategy is "join"; in the "query" branch it only registers
relation metadata and never creates join/select entries, and buildSelect() itself does not
traverse relations.

src/query-builder/SelectQueryBuilder.ts[3039-3098]
src/query-builder/SelectQueryBuilder.ts[3965-4009]
src/query-builder/SelectQueryBuilder.ts[4022-4098]

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 `relationLoadStrategy` is set to `"query"`, relation selects (e.g. `select: { category: { name: true } }`) are not added to the query at all, so the new distinct-count logic cannot include them in `COUNT(DISTINCT ...)`.
### Issue Context
- `computeSelectedColumnExpressions()` only considers `expressionMap.selects`.
- Under `relationLoadStrategy === "query"`, `buildRelations()` does not create joins nor call `buildSelect()` for relation selections.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3039-3098]
- src/query-builder/SelectQueryBuilder.ts[3965-4009]
- src/query-builder/SelectQueryBuilder.ts[4022-4098]
### Suggested fix approach
1. In `buildRelations()`, if the user provided a relation selection object (i.e. `selection && typeof selection[relationName] === "object"`), always create the join + `buildSelect(...)` for that relation **even when** `relationLoadStrategy === "query"`.
2. Keep `concatRelationMetadata(relation)` behavior for loading entities separately, but don’t let it suppress joins that are required to project selected relation columns.
3. Add a regression test that sets `relationLoadStrategy: "query"` and verifies `count()` with relation-field `select` returns the distinct-on-relation result.

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


5. VirtualColumn distinct SQL broken 🐞 Bug ≡ Correctness
Description
count({ select }) derives DISTINCT expressions as . for every selected property, which is
invalid for VirtualColumns (and other columns rendered via expressions) because the real SELECT path
uses column.query()/wrappers instead of a physical column reference. This can cause runtime SQL
errors or counts computed over the wrong expression.
Code

src/query-builder/SelectQueryBuilder.ts[R3064-3087]

Evidence
The count path converts selections into physical column references only, while the normal SELECT
generation path explicitly renders VirtualColumns via column.query(alias) (and applies other
per-driver wrappers). VirtualColumns are selectable via FindOptions select, so this mismatch is
reachable via Repository/EntityManager.count({ select: ... }).

src/query-builder/SelectQueryBuilder.ts[3031-3044]
src/query-builder/SelectQueryBuilder.ts[3064-3087]
src/query-builder/SelectQueryBuilder.ts[2935-2950]
test/functional/columns/virtual-columns/virtual-columns.test.ts[71-104]

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

## Issue description
`computeSelectedColumnExpressions()` always returns `<escapedAlias>.<escapedDatabaseName>`, which is incorrect for VirtualColumns (and other columns that are rendered as SQL expressions via `column.query()` / driver wrappers). This can make `count({ select })` generate invalid SQL or count the wrong thing.
### Issue Context
VirtualColumns are selectable via find-options `select` (see existing virtual-columns functional tests). The SELECT generation path already contains the correct logic for rendering such columns.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3031-3090]
- src/query-builder/SelectQueryBuilder.ts[2891-2977]
### Implementation notes
- When translating selected properties to DISTINCT expressions, reuse (or factor out) the same rendering logic used by `buildEscapedEntityColumnSelects`:
- If `column.isVirtualProperty && column.query`, use `(${column.query(escapedAliasName)})`.
- Apply driver-specific wrappers already applied in `buildEscapedEntityColumnSelects` (SQLite JSON wrapper, spatial conversions, etc.) so COUNT DISTINCT operates on a valid/comparable expression.
- Add a functional test covering `repository.count({ select: { <virtualColumn>: true } })` to prevent regressions.

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


6. NULLs break distinct concatenation 🐞 Bug ≡ Correctness
Description
For drivers that emulate multi-column DISTINCT by concatenating columns (MSSQL multi-col, Spanner
multi-col, and the generic fallback), NULL handling is incorrect, so COUNT(DISTINCT ...) can drop
rows entirely (NULL concat → NULL) or merge distinct combinations (NULL treated as empty string),
returning wrong distinct counts for nullable selected columns.
Code

src/query-builder/SelectQueryBuilder.ts[R3108-3144]

Evidence
The new feature counts distinct combinations of *arbitrary selected columns* when
findOptions.select is set, but the existing multi-column DISTINCT emulation relies on
concatenation without NULL-safe coercion. With nullable columns, concatenation can produce
NULL/empty-string artifacts, which changes DISTINCT semantics and can undercount.

src/query-builder/SelectQueryBuilder.ts[3031-3062]
src/query-builder/SelectQueryBuilder.ts[3092-3145]
src/metadata/ColumnMetadata.ts[87-95]

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

## Issue description
Multi-column DISTINCT emulation via concatenation is not NULL-safe. With `count({ select })`, selected columns may be nullable, and concatenation-based DISTINCT can:
- produce NULL (and be ignored by `COUNT(DISTINCT ...)`) on `||`-based drivers
- treat NULL as empty string in `CONCAT(...)`-based drivers
Both yield incorrect distinct counts.
### Issue Context
This matters specifically now because `count({ select })` can target non-primary, nullable columns, whereas the prior usage mostly involved non-null primary keys.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3092-3145]
### Implementation notes
- For concatenation-based paths (MSSQL multi-col, Spanner multi-col, generic fallback), wrap each column with a NULL-safe representation before concatenation, e.g.:
- `COALESCE(CAST(col AS <string>), '<NULL>')`
- To avoid collisions (e.g. `('<NULL>', 'x')` vs `('', 'NULLx')`), consider adding length-prefixing per component when concatenating, e.g. `LEN(component) || ':' || component` (driver-specific) or another unambiguous encoding.
- Add tests that select two columns where at least one is nullable and contains NULLs, and assert correct distinct counts across affected drivers.

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


7. QueryBuilder count semantics changed 🐞 Bug ≡ Correctness
Description
SelectQueryBuilder.computeCountExpression now returns a distinct-count of selected main-entity
columns whenever the query has explicit column selections, so
QueryBuilder.getCount()/getManyAndCount() can change from counting matching rows to counting
distinct selected values. This can silently break pagination/analytics queries that use .select(...)
for projection but still expect getCount() to return the total row/entity count.
Code

src/query-builder/SelectQueryBuilder.ts[R3037-3049]

Evidence
computeCountExpression switches to computeDistinctCountExpression based on expressionMap.selects
matching mainAlias.column.propertyPath, and SelectQueryBuilder.select(...) directly populates
expressionMap.selects with the provided selection string(s); therefore any QueryBuilder that calls
.select('alias.column') and then .getCount() will now use DISTINCT counting on those selected
columns. getManyAndCount() also uses executeCountQuery(), so pagination helpers inherit the same
behavior change.

src/query-builder/SelectQueryBuilder.ts[3031-3065]
src/query-builder/SelectQueryBuilder.ts[122-182]
src/query-builder/SelectQueryBuilder.ts[1905-1940]
src/query-builder/SelectQueryBuilder.ts[1817-1859]

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

## Issue description
`computeCountExpression()` now changes `getCount()` behavior whenever the query builder has explicit main-entity column selects (e.g. `qb.select('user.firstName')`), causing `getCount()` / `getManyAndCount()` to return a **distinct count of the projection** instead of the **row/entity count**.
### Issue Context
The PR intent is distinct-aware counting for **Repository/EntityManager count() with find-options `select`**. However, the current implementation keys off `expressionMap.selects`, which is also set by regular QueryBuilder `.select()` calls.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3031-3065]
- src/query-builder/SelectQueryBuilder.ts[122-182]
### Suggested fix approach
- In `computeCountExpression()`, only use the `selectedColumns` distinct-count path when the selection came from `setFindOptions({ select: ... })` (e.g., gate on `this.findOptions?.select`), not merely because `expressionMap.selects` is non-empty.
- Optionally, derive selected columns from `this.findOptions.select` rather than scanning `expressionMap.selects`, to avoid being affected by unrelated QueryBuilder selects/addSelects.
- Add a regression test demonstrating that `createQueryBuilder().select('alias.nonUniqueColumn').getCount()` still returns total rows unless the new distinct-count mode is explicitly enabled.

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


8. Broken FindOptionsUtils reference 🐞 Bug ≡ Correctness
Description
EntityManager.count calls FindOptionsUtils.extractFindManyOptionsAlias(...) but FindOptionsUtils is
not imported in EntityManager and extractFindManyOptionsAlias is not implemented anywhere in src,
causing a TypeScript compile error for this PR.
Code

src/entity-manager/EntityManager.ts[R1158-1162]

Evidence
The updated count() implementation references FindOptionsUtils.extractFindManyOptionsAlias while
EntityManager.ts has no corresponding import, and the FindOptionsUtils class file contains no
extractFindManyOptionsAlias implementation, so the symbol resolution fails at compile time.

src/entity-manager/EntityManager.ts[2-60]
src/entity-manager/EntityManager.ts[1143-1172]
src/find-options/FindOptionsUtils.ts[12-120]

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

## Issue description
`EntityManager.count()` references `FindOptionsUtils.extractFindManyOptionsAlias(...)`, but `FindOptionsUtils` is not imported in `EntityManager.ts` and `extractFindManyOptionsAlias` is not implemented in `src/find-options/FindOptionsUtils.ts`. This is a compile-time error.
## Issue Context
`FindManyOptions` in this codebase does not appear to carry an alias field, and other EntityManager methods (e.g., `exists`, `existsBy`, `countBy`) pass `metadata.name` directly as the query alias.
## Fix Focus Areas
- src/entity-manager/EntityManager.ts[1148-1162]
### Suggested fix
- Simplest: remove the `FindOptionsUtils.extractFindManyOptionsAlias(...)` call and pass `metadata.name` as the alias (as done elsewhere), which also removes the need for the missing import.
- Alternative: if you truly need an alias extractor, add an exported `extractFindManyOptionsAlias` implementation to `FindOptionsUtils` and import `FindOptionsUtils` in `EntityManager.ts`.

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


9. M2M distinct SQL invalid 🐞 Bug ≡ Correctness
Description
Passing a many-to-many relation property in count(distinctOn) can generate invalid SQL because the
resolved columns come from the junction entity, but the COUNT expression always qualifies them with
the main table alias. This will fail at runtime with “column does not exist” / similar SQL errors.
Code

src/query-builder/SelectQueryBuilder.ts[R3168-3183]

Evidence
getCountColumns() resolves each distinct entry using metadata.findColumnsWithPropertyPath(),
which returns relation.joinColumns for relations. For many-to-many relations, joinColumns are
explicitly taken from the junction entity (not the main entity table). Later,
computeCountExpression() blindly qualifies the returned ColumnMetadata using the main alias
(mainAlias.column), producing references to junction-table columns on the main table alias.

src/query-builder/SelectQueryBuilder.ts[3168-3191]
src/metadata/EntityMetadata.ts[772-783]
src/metadata/RelationMetadata.ts[264-271]
src/query-builder/SelectQueryBuilder.ts[3060-3095]

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

## Issue description
`count(distinctOn)` can accept relation property names (because it uses `findColumnsWithPropertyPath`), but for **many-to-many** relations that method returns join columns that belong to the **junction entity**, not the main entity table. The COUNT expression then qualifies those columns with the main alias, generating invalid SQL.
### Issue Context
- `EntityMetadata.findColumnsWithPropertyPath()` returns `relation.joinColumns`.
- `RelationMetadata` explicitly documents that for many-to-many, `joinColumns` come from the **junction entity**.
- `computeCountExpression()` always emits `${mainAlias}.${column.databaseName}`.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3168-3194]
- src/query-builder/SelectQueryBuilder.ts[3060-3166]
### Suggested direction
- In `getCountColumns()`, after `foundColumns` is resolved, **filter** out columns whose `entityMetadata` is not the passed `metadata` (main entity).
- If filtering removes all columns for a given `col`, throw a clearer error (e.g., `TypeORMError`) explaining that distinct counting currently supports only real columns and owning-side FK relations (many-to-one/one-to-one owner), not many-to-many.
- (Optional) Add a targeted test to demonstrate `count([&quot;manyToManyRelation&quot;])` fails with a clear error instead of producing invalid SQL.

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


10. Count options silently dropped ✓ Resolved 🐞 Bug ≡ Correctness
Description
• The new overloads rely on Array.isArray(countOnOrOptions) to decide whether the first arg is
countOn or options, but do not handle the runtime case repo.count(undefined, options). • In
that scenario, the options argument is ignored and the call devolves to an unfiltered count, which
is a silent correctness failure for JS users or TS code passing any/conditionally-undefined
countOn. • The issue exists at the Repository and BaseEntity forwarding layers and then in
EntityManager.count’s internal option selection.
Code

src/repository/Repository.ts[R569-580]

Evidence
Repository.count forwards only two arguments to EntityManager.count when the first parameter is
not an array; if that first parameter is undefined, the second argument (options) is dropped
entirely. EntityManager.count then determines findOptions solely from the (undefined) second
parameter in that call shape, yielding an unfiltered count. BaseEntity.count has the same
forwarding behavior.

src/repository/Repository.ts[548-580]
src/entity-manager/EntityManager.ts[1103-1126]
src/repository/BaseEntity.ts[463-471]

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

## Issue description
`count` overloads currently drop `options` when called as `count(undefined, options)` at runtime, returning an unfiltered count.
## Issue Context
Although TypeScript overload resolution discourages this call shape, it can still occur in JavaScript usage or in TypeScript when `countOn` is conditionally computed and typed as `any`.
## Fix Focus Areas
- src/repository/Repository.ts[548-580]
- src/repository/BaseEntity.ts[441-471]
- src/entity-manager/EntityManager.ts[1079-1128]
## Suggested change
Add a guard early in each implementation:
- If `countOnOrOptions === undefined` and `options !== undefined`, treat `options` as the find options and proceed as the legacy `count(options)` path.
- (Optionally) add a small regression test that calls `repo.count(undefined as any, { where: ... })` and asserts the filter is applied.

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



Remediation recommended

11. Relation select silently ignored 🐞 Bug ≡ Correctness
Description
If findOptions.select contains only relation properties, buildSelect() recognizes the relation
but does not add any selections for it, so computeCountExpression() cannot derive
selectedColumns and falls back to default counting behavior. This silently ignores the provided
select and can return a count that does not reflect the caller’s intended distinct target.
Code

src/query-builder/SelectQueryBuilder.ts[R3039-3054]

Evidence
computeCountExpression() only switches to distinct-on-selected-columns when it finds actual entity
columns in expressionMap.selects. But buildSelect() does not implement relation selection
(relation branch is commented out), so relation-only selects produce no matching mainAlias.
selections and selectedColumns remains empty.

src/query-builder/SelectQueryBuilder.ts[3031-3069]
src/query-builder/SelectQueryBuilder.ts[3972-4016]

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

## Issue description
`count({ select: { relation: {...} } })` is accepted but relation selections are ignored by `buildSelect()`, causing `computeCountExpression()` to fall back to default counting. This is silent and can surprise callers.
### Issue Context
The PR explicitly aims to support entity + embedded columns; relations are not supported. The implementation should fail fast (or at least be explicit) when the requested distinct target cannot be constructed.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3031-3069]
- src/query-builder/SelectQueryBuilder.ts[3972-4016]
### Suggested fix
Add validation during find-options processing (e.g., in `buildSelect()` or before calling it) to detect relation keys inside `findOptions.select` and throw a clear error for `count()`/`getCount()` usage (or, at minimum, when `findOptions.select` is present but resolves to zero entity/embedded columns). This prevents silent fallback to default counting semantics.

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


12. Distinct concat collision risk 🐞 Bug ≡ Correctness
Description
For MSSQL/Spanner/other fallback drivers, multi-column DISTINCT count is implemented via
concatenation with a fixed delimiter ('|;|'). With the new API enabling DISTINCT on arbitrary
columns (often strings), different value tuples can collide (e.g., ('a|;|b','c') vs
('a','b|;|c')), causing silent undercounting.
Code

src/query-builder/SelectQueryBuilder.ts[R3117-3127]

Evidence
When multiple columns are counted distinctly on MSSQL/Spanner/fallback, values are
string-concatenated with a fixed delimiter and then distinct-counted. This approach is not
collision-safe for arbitrary string data; the new feature explicitly allows distinct counting on
non-PK columns, making collisions more plausible in real datasets.

src/query-builder/SelectQueryBuilder.ts[3114-3129]
src/query-builder/SelectQueryBuilder.ts[3152-3165]
src/entity-manager/EntityManager.ts[1116-1123]

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

## Issue description
Current multi-column DISTINCT counting for MSSQL/Spanner/fallback drivers concatenates column values with a fixed delimiter (`&#x27;|;|&#x27;`) and then applies `COUNT(DISTINCT ...)`. For arbitrary string data, this can produce collisions and silently undercount.
### Issue Context
This risk existed previously for composite primary keys, but the new API makes it far more likely because callers can now select arbitrary columns (including user-controlled strings) to count distinctly.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3060-3166]
- src/query-builder/SelectQueryBuilder.ts[3196-3210]
### Suggested direction
Prefer a collision-free strategy for drivers without native multi-column DISTINCT support:
- Implement a `SELECT COUNT(*) FROM (SELECT DISTINCT col1, col2 ... FROM &lt;original query without order/limit&gt;) sub` strategy for the `distinctColumns` case (especially when `distinctColumns.length &gt; 1`).
- This avoids delimiter collisions and type-casting pitfalls.
- If a subquery approach is not feasible for some drivers, at minimum implement a collision-resistant encoding (e.g., length-prefixed encoding per column) rather than a plain delimiter join.
- Add a regression test that demonstrates a collision case on at least one affected driver (or at minimum unit-test the produced SQL shape for the subquery path).

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


13. Mongo distinct overload footgun 🐞 Bug ≡ Correctness
Description
DataSource.manager is typed as EntityManager even on MongoDB connections, but MongoDB uses
MongoEntityManager.count(entity, query, options). The new `EntityManager.count(entity,
distinctOnArray, options) overload can therefore compile against dataSource.manager` and at
runtime pass an array into MongoDB’s count() as the filter argument, which is forwarded to the
driver without validation.
Code

src/entity-manager/EntityManager.ts[R1082-1123]

Evidence
Type-wise, DataSource.manager is always EntityManager, so the new distinct overload is available
even when the runtime manager instance is actually a MongoEntityManager. MongoEntityManager’s
count interprets the second argument as a Mongo Filter and forwards it to the query runner
without guarding against arrays. This makes dataSource.manager.count(User, ["field"]) a plausible
new runtime error path for Mongo users following the new API shape.

src/data-source/DataSource.ts[83-87]
src/data-source/DataSource.ts[165-179]
src/entity-manager/MongoEntityManager.ts[542-549]
src/driver/mongodb/MongoQueryRunner.ts[195-203]
src/entity-manager/EntityManager.ts[1082-1123]

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

## Issue description
With the new `EntityManager.count(entity, distinctOnArray, options)` overload, code written against `dataSource.manager` (typed as `EntityManager`) can now pass an array as the second argument. On MongoDB connections, runtime dispatch goes to `MongoEntityManager.count(entity, query, options)`, where that array becomes the `query` filter and is forwarded to the driver without validation.
### Issue Context
- `DataSource.manager` is always typed as `EntityManager`.
- MongoDB has a different `count()` signature and semantics.
### Fix Focus Areas
- src/entity-manager/MongoEntityManager.ts[542-549]
- src/data-source/DataSource.ts[83-87]
### Suggested direction
- Add an early runtime check in `MongoEntityManager.count()`:
- If `Array.isArray(query)`, throw a `TypeORMError` with a clear message (e.g., &quot;MongoDB EntityManager.count does not support DISTINCT column arrays; use a MongoDB aggregation instead&quot;).
- Consider also updating docs or typings so the new DISTINCT overload is clearly SQL-only (but the runtime guard is the most direct safety net).

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


View more (3)
14. Distinct typing too narrow 🐞 Bug ≡ Correctness
Description
Docs and runtime support string property paths for distinct counting, but the new public API types
use (keyof Entity)[], which can’t represent dotted paths (e.g., embedded columns) without unsafe
casts.
Code

src/entity-manager/EntityManager.ts[R1082-1086]

Evidence
Documentation explicitly describes passing “entity property paths”, and the query builder resolves
strings using findColumnsWithPropertyPath(propertyPath: string). However,
EntityManager.count/Repository.count expose the distinct list as (keyof Entity)[], which
excludes dotted property paths supported by
ColumnMetadata.propertyPath/findColumnsWithPropertyPath.

docs/docs/working-with-entity-manager/5-entity-manager-api.md[304-317]
src/entity-manager/EntityManager.ts[1082-1086]
src/query-builder/SelectQueryBuilder.ts[3168-3183]
src/repository/Repository.ts[559-562]

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 distinct-count API is documented and implemented around string property paths, but the public method signatures constrain the distinct column list to `(keyof Entity)[]`, which prevents valid dotted property paths (e.g., embedded columns) from type-checking.
### Issue Context
`SelectQueryBuilder` ultimately resolves `distinctColumns` as `string[]` via `metadata.findColumnsWithPropertyPath`, so runtime can support dotted `propertyPath` strings.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[1071-1124]
- src/repository/Repository.ts[553-587]
- src/repository/BaseEntity.ts[445-478]
- docs/docs/working-with-entity-manager/5-entity-manager-api.md[304-317]
### Suggested fix approach
1. Add overloads that accept `distinctOn: string[]` (or `(keyof Entity | string)[]`) in `EntityManager.count`, `Repository.count`, and `BaseEntity.count`.
2. Keep existing `keyof Entity` overloads if desired, but ensure the implementation parameter union includes `string[]`.
3. Ensure docs match the final signature (explicitly mention string property paths, including embedded paths, if supported).
4. Add/adjust tests to cover a dotted property path case (embedded) to prevent regressions.

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


15. Non-distinct countOn semantics ✓ Resolved 🐞 Bug ➹ Performance
Description
• When countOn is provided with distinct: false, the builder still generates driver-specific
COUNT() over the provided columns instead of using COUNT(1). • This is unnecessary work
(especially for join-free queries) and introduces cross-driver differences because the counted
expression varies by driver (e.g., CONCAT(...) vs || concatenation vs row constructors). • Since
the docs position distinct as the switch that controls COUNT(DISTINCT ...) for countOn, the
non-distinct mode can safely be implemented as COUNT(1) while still counting duplicates introduced
by joins.
Code

src/query-builder/SelectQueryBuilder.ts[R3098-3118]

Evidence
computeCountExpression disables the COUNT(1) fast-path whenever countColumns.length > 0 and
then emits different expression forms per driver. For MySQL it uses COUNT(CONCAT(...)) when not
distinct, and the fallback path uses string concatenation with a delimiter. This creates unnecessary
computation and makes non-distinct counts depend on driver-specific expression building rather than
a consistent COUNT(1) row-count.

src/query-builder/SelectQueryBuilder.ts[3098-3107]
src/query-builder/SelectQueryBuilder.ts[3137-3148]
src/query-builder/SelectQueryBuilder.ts[3195-3201]

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

## Issue description
`countOn` currently forces expression-based counting even when `distinct` is false. This adds overhead and yields driver-specific behavior.
## Issue Context
Docs describe `distinct` as the switch that determines whether `COUNT(DISTINCT ...)` is used when a column list is supplied.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3098-3202]
## Suggested change
- In `computeCountExpression()`, if `countColumns.length &amp;amp;gt; 0` and `this.expressionMap.selectDistinct` is false, return `COUNT(1)` (or `COUNT(*)`) instead of building expression-based counts.
- Keep the current column-based generation only for the distinct case (`selectDistinct === true`).
- Consider adding/adjusting tests for `countOn` + `distinct:false` to assert it counts rows (including join duplicates) irrespective of the chosen columns.

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


16. Slow test data setup 🐞 Bug ➹ Performance
Description
• The new aggregate tests insert 100 User rows per connection using 100 sequential save() calls.
• With many test connections/drivers, this can significantly increase suite runtime and make CI more
timeout-prone. • The same dataset can be created via a single batched save([...])/insert([...])
per connection.
Code

test/functional/repository/aggregate-methods/repository-aggregate-methods.test.ts[R31-41]

Evidence
The global before() hook creates 100 users by awaiting each save() call inside a loop, repeated
for each connection. This is avoidable overhead in a hot-path test setup.

test/functional/repository/aggregate-methods/repository-aggregate-methods.test.ts[31-41]

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 suite performs 100 sequential `save()` operations per connection for seeding `User` data.
## Issue Context
This runs in a `before()` hook and scales with the number of enabled drivers.
## Fix Focus Areas
- test/functional/repository/aggregate-methods/repository-aggregate-methods.test.ts[20-41]
## Suggested change
- Build an array of 100 `User` objects and call `await repo.save(users)` once per connection, or use `await repo.insert(users)` if supported by the test’s constraints.
- (Optional) Do the same batching for `Post` seeding if desired for consistency.

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



Informational

17. Misleading primary-column comment 🐞 Bug ⚙ Maintainability
Description
computeDistinctCountExpression’s fallback comment still says it counts distinct across “primary
columns concatenated”, but the method now operates on arbitrary column expressions (including
user-selected columns). This is misleading and makes future maintenance riskier.
Code

src/query-builder/SelectQueryBuilder.ts[R3137-3141]

Evidence
The method signature is now generalized to columns: string[] and is invoked with selected columns
when findOptions.select is present, but the fallback comment still describes primary-column
concatenation.

src/query-builder/SelectQueryBuilder.ts[3027-3057]
src/query-builder/SelectQueryBuilder.ts[3088-3141]

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 comment in `computeDistinctCountExpression` still refers to concatenating *primary columns*, but the method now receives an arbitrary `columns: string[]` and is used for distinct counts over user-selected columns.
### Issue Context
This can confuse reviewers/maintainers and lead to incorrect assumptions when modifying distinct-count behavior.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[3088-3141]
### Suggested fix
Update the comment to describe the current behavior accurately (e.g., “selected columns” / “provided columns”), and optionally mention that for some drivers multi-column distinct is emulated via concatenation (with any limitations if you keep that approach).

ⓘ 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/repository/Repository.ts Resolved
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit a0410c0

@Cprakhar Cprakhar changed the title feat: add aggregate method count in EntityManager feat: update method count in EntityManager to support DISTINCT Feb 7, 2026
@Cprakhar
Cprakhar force-pushed the feat/count-with-distinct branch from a0410c0 to 9f0ec68 Compare March 7, 2026 09:29
@sonarqubecloud

sonarqubecloud Bot commented Mar 7, 2026

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 9f0ec68

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 9f0ec68

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 80.288% (+0.02%) from 80.272%
when pulling 9f0ec68 on Cprakhar:feat/count-with-distinct
into a84e993 on typeorm:master.

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 3202523

@Cprakhar
Cprakhar marked this pull request as draft May 4, 2026 19:19
@Cprakhar
Cprakhar force-pushed the feat/count-with-distinct branch from 3202523 to 2bf2026 Compare May 4, 2026 19:20
@Cprakhar Cprakhar changed the title feat: update method count in EntityManager to support DISTINCT feat: support distinct count May 4, 2026
@Cprakhar Cprakhar self-assigned this May 4, 2026
@Cprakhar
Cprakhar marked this pull request as ready for review May 4, 2026 20:25
@Cprakhar
Cprakhar requested review from G0maa, alumni, gioboa and smith-xyz May 5, 2026 17:39
@Cprakhar
Cprakhar force-pushed the feat/count-with-distinct branch from 5442fa6 to a159299 Compare May 6, 2026 20:58
@Cprakhar

Cprakhar commented May 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

qodo's #14 is valid. Need a little more work.

@VirtualColumn in COUNT works in some DBs (SQLite) but not in others (e.g., Postgres). Not tested all DBs. Will keep it in the expression.

@Cprakhar
Cprakhar force-pushed the feat/count-with-distinct branch from 70f5358 to bceb1ee Compare June 17, 2026 14:29

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

useful, glad this is getting added!

@smith-xyz
smith-xyz merged commit cca26a9 into typeorm:master Jun 25, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Jun 25, 2026
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.

Easier way to make SELECT COUNT(DISTINCT()) queries

6 participants