Skip to content

Qualify columns with table alias in aggregate SELECT clauses for joined tables - #11817

Closed
Cprakhar wants to merge 0 commit into
typeorm:masterfrom
Cprakhar:master
Closed

Cprakhar wants to merge 0 commit into
typeorm:masterfrom
Cprakhar:master

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Dec 3, 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

@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

Alias Naming

The alias is set to metadata.name which is the entity name. This could potentially cause issues if the entity name contains special characters or conflicts with SQL reserved keywords. Consider using a sanitized or escaped alias name, or verify that metadata.name is always safe to use as a table alias.

const alias = metadata.name
const result = await this.createQueryBuilder(entityClass, alias)
Double Escaping Risk

The alias is escaped using this.connection.driver.escape() in the SELECT clause. Verify that this is the correct escaping method for table aliases (as opposed to column names or identifiers), and ensure it doesn't cause double-escaping issues if the alias was already processed elsewhere in the query builder chain.

`${fnName}(${this.connection.driver.escape(
    alias,
)}.${this.connection.driver.escape(column.databaseName)})`,

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

qodo-free-for-open-source-projects Bot commented Dec 3, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 245afa7

CategorySuggestion                                                                                                                                    Impact
General
Conditionally qualify columns with alias

Conditionally qualify the aggregate function's column with the table alias only
when joins are present in the query. This avoids potential issues and generates
cleaner SQL.

src/entity-manager/EntityManager.ts [1093-1105]

 const qb = this.createQueryBuilder(entityClass, metadata.name)
 qb.setFindOptions({ where })
 
 const alias = qb.alias
+const hasJoins = qb.expressionMap.joinAttributes.length > 0
+
+const columnRef = hasJoins 
+    ? `${this.connection.driver.escape(alias)}.${this.connection.driver.escape(column.databaseName)}`
+    : this.connection.driver.escape(column.databaseName)
 
 const result = await qb
-    .select(
-        `${fnName}(${this.connection.driver.escape(
-            alias,
-        )}.${this.connection.driver.escape(column.databaseName)})`,
-        fnName,
-    )
+    .select(`${fnName}(${columnRef})`, fnName)
     .getRawOne()
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the PR's change always qualifies the column with an alias. While this fixes the issue with joins, the suggestion's proposal to do so conditionally based on the presence of joins makes the generated SQL cleaner and more robust for cases without relations.

Low
  • More

Previous suggestions

✅ Suggestions up to commit cbdb859
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use the query builder's actual alias
Suggestion Impact:The commit directly implements the suggestion by creating the query builder first, calling setFindOptions, then retrieving the alias from the query builder instance (qb.alias) instead of using the hardcoded metadata.name value.

code diff:

-        const alias = metadata.name
-        const result = await this.createQueryBuilder(entityClass, alias)
-            .setFindOptions({ where })
+
+        const qb = this.createQueryBuilder(entityClass, metadata.name)
+        qb.setFindOptions({ where })
+
+        const alias = qb.alias
+
+        const result = await qb

To prevent potential SQL errors, retrieve the alias from the query builder
instance after setFindOptions is called, instead of using the hardcoded
metadata.name.

src/entity-manager/EntityManager.ts [1092-1101]

-const alias = metadata.name
-const result = await this.createQueryBuilder(entityClass, alias)
-    .setFindOptions({ where })
+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()

[Suggestion processed]

Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential bug where the hardcoded alias might differ from the one generated by the query builder after processing relations, leading to SQL errors. Applying this change makes the implementation more robust.

Medium

@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 3, 2025 •

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

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

commit: 245afa7

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 80.771% (+0.001%) from 80.77%
when pulling 245afa7 on Cprakhar:master
into 73fda41 on typeorm:master.

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

3 participants