Skip to content

fix: raw select query with correctly ordered selected columns - #11902

Merged
gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/select-columns-wrong-order-sql
Jan 12, 2026
Merged

gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/select-columns-wrong-order-sql

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 8, 2026

Copy link
Copy Markdown
Collaborator

Description of Change

This PR addresses the order in which columns are returned by the getQuery() or getSql() methods when using select() and addSelect().

Purpose of the Change

The following TypeScript code snippet demonstrates the intended outcome:

const sql = connection
                    .createQueryBuilder(Post, "post")
                    .select("post.description", "post_description")
                    .addSelect("post.title", "post_title")
                    .addSelect("post.id", "post_id")
                    .getQuery();

Before the Change:

SELECT "post"."id" AS "post_id", 
       "post"."title" AS "post_title", 
       "post"."description" AS "post_description"
FROM "post" "post";

After the Change:

SELECT "post"."description" AS "post_description", 
       "post"."title" AS "post_title", 
       "post"."id" AS "post_id"
FROM "post" "post";

Pull Request Checklist

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

Fixes #8466

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

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

8466 - PR Code Verified

Compliant requirements:

  • The order of selected columns in emitted SQL now matches the order they were added via select() and addSelect() methods
  • Fix preserves column order when using getQuery() method
  • Fix works with both select() with alias and addSelect() combinations

Requires further human verification:

  • Verify the fix works correctly with SQL Server driver specifically (the only driver marked as reproducible in the issue)
  • Test the fix in actual UNION ALL scenarios to ensure column order is preserved correctly
  • Verify the fix doesn't break existing functionality with other database drivers
  • Test with more complex scenarios involving joins, subqueries, and multiple entities
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Duplicates

The code adds columns from selectedColumnsOrder to the columns array, but columns from metadata.columns.filter((column) => column.isSelect === true) were already added when hasMainAlias is true. This could result in duplicate columns if a column has isSelect === true and is also in the selects list. Need to verify if duplicates are handled elsewhere or if this creates an issue.

    columns.push(
        ...metadata.columns.filter(
            (column) => column.isSelect === true,
        ),
    )
}

const validPaths = new Set(
    metadata.columns.map((col) => `${aliasName}.${col.propertyPath}`),
)
const selectedColumnsOrder = this.expressionMap.selects
    .filter((select) => validPaths.has(select.selection))
    .map(
        (select) =>
            metadata.columns.find(
                (col) =>
                    `${aliasName}.${col.propertyPath}` ===
                    select.selection,
            )!,
    )
columns.push(...selectedColumnsOrder)
Non-null Assertion

The non-null assertion operator on line 2883 assumes that find() will always return a column, but this might not be guaranteed if the validPaths Set doesn't perfectly match the filtered selects. Consider adding error handling or validation to prevent potential runtime errors.

        metadata.columns.find(
            (col) =>
                `${aliasName}.${col.propertyPath}` ===
                select.selection,
        )!,
)

@pkg-pr-new

pkg-pr-new Bot commented Jan 8, 2026 •

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

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

commit: e0e18f0

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

qodo-free-for-open-source-projects Bot commented Jan 8, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to e0e18f0

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent duplicate column selections

To prevent duplicate columns in the generated SELECT statement, filter out
columns that have already been added to the columns array before pushing new
ones.

src/query-builder/SelectQueryBuilder.ts [2872-2882]

 const columnsMap = new Map(
     metadata.columns.map((col) => [
         `${aliasName}.${col.propertyPath}`,
         col,
     ]),
 )
+const existingColumns = new Set(columns.map(col => col.propertyPath))
 columns.push(
     ...this.expressionMap.selects
         .map((select) => columnsMap.get(select.selection))
-        .filter((col): col is ColumnMetadata => !!col),
+        .filter((col): col is ColumnMetadata => !!col && !existingColumns.has(col.propertyPath)),
 )

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a scenario where duplicate columns can be added to the SELECT clause, which is a valid bug that leads to incorrect SQL generation. The proposed fix is both correct and efficient.

Medium
  • More

Previous suggestions

Suggestions up to commit b3ffaa7
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent duplicate column selections

To prevent duplicate columns in the final query, use a Set to track
already-added column property paths and filter out any columns that have already
been added.

src/query-builder/SelectQueryBuilder.ts [2872-2882]

 const columnsMap = new Map(
     metadata.columns.map((col) => [
         `${aliasName}.${col.propertyPath}`,
         col,
     ]),
 )
+const addedPaths = new Set(columns.map(col => col.propertyPath))
 columns.push(
     ...this.expressionMap.selects
         .map((select) => columnsMap.get(select.selection))
-        .filter((col): col is ColumnMetadata => !!col),
+        .filter((col): col is ColumnMetadata => !!col && !addedPaths.has(col.propertyPath)),
 )
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a logic flaw in the PR where duplicate columns could be selected if an entity alias and its specific columns are both selected, and provides a valid fix.

Medium
Suggestions up to commit 5fa5ef8
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent duplicate column selections

To prevent duplicate column selections, check if a column is already in the
columns array before adding it. This can be achieved by using a Set to track
added columns.

src/query-builder/SelectQueryBuilder.ts [2872-2882]

 const columnsMap = new Map(
     metadata.columns.map((col) => [
         `${aliasName}.${col.propertyPath}`,
         col,
     ]),
 )
+const columnsSet = new Set(columns.map(col => col.propertyPath))
 columns.push(
     ...this.expressionMap.selects
         .map((select) => columnsMap.get(select.selection))
-        .filter((col): col is ColumnMetadata => !!col),
+        .filter((col): col is ColumnMetadata => !!col && !columnsSet.has(col.propertyPath)),
 )
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug where columns can be added multiple times to the select list, which could lead to incorrect behavior or redundant SQL. The proposed fix using a Set is a valid and clean way to prevent these duplicates.

Medium
✅ Suggestions up to commit 51c4f71
CategorySuggestion                                                                                                                                    Impact
General
✅ Improve performance by using a Map
Suggestion Impact:The commit implements the core suggestion by replacing the Set-based filtering with nested find() loop with a Map-based lookup. The implementation uses `columnsMap` instead of `validPaths`, maps columns by property path, and uses `columnsMap.get()` for O(1) lookups. The commit differs slightly in implementation style (using map().filter() chain instead of a for loop) but achieves the same performance improvement goal.

code diff:

-        const validPaths = new Set(
-            metadata.columns.map((col) => `${aliasName}.${col.propertyPath}`),
+        const columnsMap = new Map(
+            metadata.columns.map((col) => [
+                `${aliasName}.${col.propertyPath}`,
+                col,
+            ]),
         )
-        const selectedColumnsOrder = this.expressionMap.selects
-            .filter((select) => validPaths.has(select.selection))
-            .map(
-                (select) =>
-                    metadata.columns.find(
-                        (col) =>
-                            `${aliasName}.${col.propertyPath}` ===
-                            select.selection,
-                    )!,
-            )
-        columns.push(...selectedColumnsOrder)
+        columns.push(
+            ...this.expressionMap.selects
+                .map((select) => columnsMap.get(select.selection))
+                .filter((col): col is ColumnMetadata => !!col),
+        )

To improve performance, replace the nested loop logic for finding selected
columns with a more efficient Map-based lookup. First, build a Map of columns
keyed by their property path, then iterate through the selections to retrieve
the columns.

src/query-builder/SelectQueryBuilder.ts [2872-2885]

-const validPaths = new Set(
-    metadata.columns.map((col) => `${aliasName}.${col.propertyPath}`),
+const columnsByPath = new Map(
+    metadata.columns.map((col) => [
+        `${aliasName}.${col.propertyPath}`,
+        col,
+    ]),
 )
-const selectedColumnsOrder = this.expressionMap.selects
-    .filter((select) => validPaths.has(select.selection))
-    .map(
-        (select) =>
-            metadata.columns.find(
-                (col) =>
-                    `${aliasName}.${col.propertyPath}` ===
-                    select.selection,
-            )!,
-    )
-columns.push(...selectedColumnsOrder)
 
+for (const select of this.expressionMap.selects) {
+    const col = columnsByPath.get(select.selection)
+    if (col) {
+        columns.push(col)
+    }
+}
+
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a performance bottleneck in the newly added code and proposes a valid, more efficient solution using a Map to avoid a nested loop, improving the algorithm's time complexity.

Low

@coveralls

coveralls commented Jan 8, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.869% (-0.001%) from 80.87%
when pulling b3ffaa7 on Cprakhar:fix/select-columns-wrong-order-sql
into fdcbcba on typeorm:master.

@Cprakhar
Cprakhar force-pushed the fix/select-columns-wrong-order-sql branch from 51c4f71 to 5fa5ef8 Compare January 8, 2026 11:36
…mprove performance for finding selected columns
@Cprakhar
Cprakhar force-pushed the fix/select-columns-wrong-order-sql branch from 5fa5ef8 to b3ffaa7 Compare January 8, 2026 12:25

@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 @Cprakhar it looks great to me 👏

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

🐞 Bugs (1) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Action Required

1. Duplicate Columns in Selection Array 🐞 Bug
Description
• When a user selects an entity by alias (e.g., .select('post')) AND then explicitly selects
  individual columns from the same entity (e.g., .addSelect('post.id')), the code will add duplicate
  columns to the columns array
• The hasMainAlias block (lines 2864-2870) adds all columns with isSelect=true when the alias is
  selected
• Then lines 2878-2882 iterate through expressionMap.selects and add columns again based on the Map
  lookup, including columns already added by the hasMainAlias block
• This causes duplicate ColumnMetadata objects in the columns array, which can break the indexOf
  check at line 2893 for detecting non-selected primary columns

correctness

Code

src/query-builder/SelectQueryBuilder.ts[R2878-2882]

        columns.push(
-            ...metadata.columns.filter((column) => {
-                return this.expressionMap.selects.some(
-                    (select) =>
-                        select.selection ===
-                        aliasName + "." + column.propertyPath,
-                )
-            }),
+            ...this.expressionMap.selects
+                .map((select) => columnsMap.get(select.selection))
+                .filter((col): col is ColumnMetadata => !!col),
        )
Evidence
The code flow demonstrates the duplicate column issue: (1) When .select('post') is called, it adds
{selection: 'post'} to expressionMap.selects (line 171-173 in select method). (2) When
.addSelect('post.id') is called, it adds {selection: 'post.id'} to expressionMap.selects (line
221-224 in addSelect method). (3) In buildEscapedEntityColumnSelects, hasMainAlias becomes true
because expressionMap.selects contains an entry with selection === 'post' (line 2859-2861). (4)
Lines 2864-2870 push all columns with isSelect=true, including the 'id' column. (5) Lines 2878-2882
then map over expressionMap.selects, and when processing the 'post.id' entry,
columnsMap.get('post.id') returns the same 'id' column metadata object again. (6) This results in
the 'id' column being in the columns array twice. (7) The indexOf check at line 2893 will only find
the first occurrence, potentially missing that a primary column was already added.

src/query-builder/SelectQueryBuilder.ts[2859-2861]
src/query-builder/SelectQueryBuilder.ts[2864-2870]
src/query-builder/SelectQueryBuilder.ts[2878-2882]
src/query-builder/SelectQueryBuilder.ts[2891-2895]
src/query-builder/SelectQueryBuilder.ts[171-173]
src/query-builder/SelectQueryBuilder.ts[221-224]

Agent Prompt
## Issue Description
The buildEscapedEntityColumnSelects method adds duplicate columns when a user selects an entity by alias and then explicitly selects individual columns from the same entity. For example, `.select('post').addSelect('post.id')` will add the 'id' column twice to the columns array.

## Issue Context
When hasMainAlias is true (meaning expressionMap.selects contains an entry like 'post'), the code adds all columns with isSelect=true. Then it iterates through expressionMap.selects again and adds columns based on Map lookup, which can include the same columns already added.

## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2878-2882]: Modify the logic to skip columns that are already in the array, or filter out entries from expressionMap.selects that match columns already added by the hasMainAlias block
- src/query-builder/SelectQueryBuilder.ts[2864-2870]: Consider using a Set to track added columns to prevent duplicates

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


Grey Divider

Qodo Logo

@gioboa
gioboa merged commit b0dd92d into typeorm:master Jan 12, 2026
38 checks passed
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
@Cprakhar
Cprakhar deleted the fix/select-columns-wrong-order-sql branch January 24, 2026 20:06
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 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.

Emitted SQL has selected columns in wrong order

5 participants