Skip to content

fix: fix up aggregate methods ambiguous column - #11822

Merged
gioboa merged 5 commits into
typeorm:masterfrom
Cprakhar:fix/aggregate-methods-ambiguous-column
Dec 4, 2025
Merged

gioboa merged 5 commits into
typeorm:masterfrom
Cprakhar:fix/aggregate-methods-ambiguous-column

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Dec 4, 2025

Copy link
Copy Markdown
Collaborator

Description of change

  • What the change is intended to do:
    This PR fixes an issue where repository aggregation methods sum, average, minimum and maximum throw "ambiguous column reference" errors when used with WHERE clauses that filter by relations.

  • Why this change is needed:
    When using aggregation methods with relation filters (e.g., repository.maximum('id', { author: { id: 1 } }), TypeORM automatically creates LEFT JOINs to the related tables. However, the SELECT clause was generating unqualified column names like MAX("id") instead of MAX("TableAlias"."id"). This caused database errors when multiple tables in the join had columns with the same name (which is very common with id columns).

Pull-Request Checklist

  1. Applied the fix to EntityManager.ts
  2. Verified the fix resolves the issue with the reproduction case
  3. Added comprehensive tests:
    • GitHub issue-specific test: test/github-issues/11797
    • Functional tests: aggregate-methods-with-relations
  • Code is up-to-date with the master branch
  • This pull request links relevant issues: 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)

Current behavior:

SELECT MAX("id") AS "MAX" FROM "table" "Alias" 
  LEFT JOIN "related_table" "Alias__related" ON ... 
WHERE ...
-- ERROR: column reference "id" is ambiguous

New behavior:

SELECT MAX("Alias"."id") AS "MAX" FROM "table" "Alias" 
  LEFT JOIN "related_table" "Alias__related" ON ... 
WHERE ...
-- SUCCESS: Returns correct aggregated value

Fixes #11797

Note
This PR replaces #11817
History was rewritten, so GitHub auto-closed the previous PR.

…erences

When using repository aggregation methods (sum, average, minimum, maximum)
with WHERE clauses that include relations, TypeORM creates LEFT JOINs to
related tables. Previously, the SELECT clause used unqualified column names
like MAX("id"), which caused "ambiguous column reference" errors when multiple
tables had columns with the same name.

This fix qualifies the column name with the table alias in the SELECT clause,
generating SQL like MAX("TableName"."id") instead of MAX("id").

Closes typeorm#11797
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Query Builder Reuse

The query builder is created and configured with setFindOptions, but then only the alias is extracted before calling .select() and .getRawOne(). Verify that the WHERE clause from setFindOptions is properly applied to the final query, as the code structure suggests the query builder chain might not be complete.

const qb = this.createQueryBuilder(entityClass, metadata.name)
qb.setFindOptions({ where })

const alias = qb.alias

const result = await qb
    .select(
        `${fnName}(${this.connection.driver.escape(
            alias,
        )}.${this.connection.driver.escape(column.databaseName)})`,
        fnName,
    )
    .getRawOne()
Missing Method Chain

The qb.select() call on line 1099 appears disconnected from the query builder instance created on line 1093. The code should verify that qb.select().getRawOne() properly chains the operations, as the formatting suggests potential method chaining issues that could result in the WHERE clause not being applied.

const result = await qb
    .select(
        `${fnName}(${this.connection.driver.escape(
            alias,
        )}.${this.connection.driver.escape(column.databaseName)})`,
        fnName,
    )
    .getRawOne()

@Cprakhar Cprakhar changed the title Fix/aggregate methods ambiguous column Fix aggregate methods ambiguous column Dec 4, 2025
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@pkg-pr-new

pkg-pr-new Bot commented Dec 4, 2025

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

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

commit: 287cf69

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your help @Cprakhar

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 80.77%. remained the same
when pulling 287cf69 on Cprakhar:fix/aggregate-methods-ambiguous-column
into 73fda41 on typeorm:master.

@gioboa
gioboa requested a review from pkuczynski December 4, 2025 21:42
@gioboa gioboa changed the title Fix aggregate methods ambiguous column fix: fix up aggregate methods ambiguous column Dec 4, 2025
@gioboa
gioboa merged commit 6e34756 into typeorm:master Dec 4, 2025
@dmurvihill

Copy link
Copy Markdown

Thanks @Cprakhar! Much appreciated.

@Cprakhar
Cprakhar deleted the fix/aggregate-methods-ambiguous-column branch January 7, 2026 15:01
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 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.

Repository aggregations with joins render ambiguous column references

5 participants