Skip to content

fix(query-builder): resolve column lookup when using database column name in addOrderBy - #11904

Merged
gioboa merged 2 commits into
typeorm:masterfrom
smith-xyz:gh-11808
Jan 21, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
smith-xyz:gh-11808

Conversation

@smith-xyz

Copy link
Copy Markdown
Collaborator

Description of change

When using addOrderBy with a database column name (e.g., "p.created_at")
instead of the property name ("p.createdAt") combined with pagination
(skip/take), the query would crash with "Cannot read properties of
undefined (reading 'databaseName')".

The fix adds a fallback to findColumnWithDatabaseName when
findColumnWithPropertyPath doesn't find the column.

Fixes #11808

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 tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

@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

Null Safety

The code uses the nullish coalescing operator to fall back to findColumnWithDatabaseName, but doesn't handle the case where both methods return null/undefined. While there's a fallback to use propertyPath directly, this could lead to incorrect SQL generation if the property path doesn't match the actual database column name. Consider adding validation or error handling for invalid column references.

    alias.metadata.findColumnWithPropertyPath(
        propertyPath,
    ) ??
    alias.metadata.findColumnWithDatabaseName(propertyPath)
const databaseName = column
    ? column.databaseName
    : propertyPath
Code Duplication

The same column lookup logic (with fallback to findColumnWithDatabaseName and databaseName extraction) is duplicated in two separate locations within the same file. This creates a maintenance burden and potential for inconsistency. Consider extracting this logic into a helper method.

                alias.metadata.findColumnWithPropertyPath(
                    propertyPath,
                ) ??
                alias.metadata.findColumnWithDatabaseName(propertyPath)
            const databaseName = column
                ? column.databaseName
                : propertyPath
            return (
                this.escape(parentAlias) +
                "." +
                this.escape(
                    DriverUtils.buildAlias(
                        this.connection.driver,
                        undefined,
                        aliasName,
                        databaseName,
                    ),
                )
            )
        } else {
            if (
                this.expressionMap.selects.find(
                    (select) =>
                        select.selection === orderCriteria ||
                        select.aliasName === orderCriteria,
                )
            )
                return (
                    this.escape(parentAlias) +
                    "." +
                    this.escape(orderCriteria)
                )

            return ""
        }
    })
    .join(", ")

const orderByObject: OrderByCondition = {}
Object.keys(orderBys).forEach((orderCriteria) => {
    if (orderCriteria.indexOf(".") !== -1) {
        const criteriaParts = orderCriteria.split(".")
        const aliasName = criteriaParts[0]
        const propertyPath = criteriaParts.slice(1).join(".")
        const alias = this.expressionMap.findAliasByName(aliasName)
        const column =
            alias.metadata.findColumnWithPropertyPath(propertyPath) ??
            alias.metadata.findColumnWithDatabaseName(propertyPath)
        const databaseName = column ? column.databaseName : propertyPath

@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@11904
    

commit: bb4a81e

@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 bb4a81e

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for alias

Add a null check for the alias variable before accessing its metadata property
to prevent a potential runtime error.

src/query-builder/SelectQueryBuilder.ts [3739-3746]

+const alias = this.expressionMap.findAliasByName(aliasName)
+if (!alias) {
+    return orderCriteria
+}
 const column =
     alias.metadata.findColumnWithPropertyPath(
         propertyPath,
     ) ??
     alias.metadata.findColumnWithDatabaseName(propertyPath)
 const databaseName = column
     ? column.databaseName
     : propertyPath
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential null reference error if findAliasByName returns undefined, improving the code's robustness against invalid orderBy criteria.

Medium
  • More

Previous suggestions

Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for alias

Add a null check for the alias variable before accessing its metadata property
to prevent a potential runtime error if the alias is not found.

src/query-builder/SelectQueryBuilder.ts [3736-3743]

-const column =
-    alias.metadata.findColumnWithPropertyPath(
-        propertyPath,
-    ) ??
-    alias.metadata.findColumnWithDatabaseName(propertyPath)
+const column = alias
+    ? alias.metadata.findColumnWithPropertyPath(
+          propertyPath,
+      ) ??
+      alias.metadata.findColumnWithDatabaseName(propertyPath)
+    : null
 const databaseName = column
     ? column.databaseName
     : propertyPath
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential runtime error if an invalid alias is used in an orderBy clause, which would cause findAliasByName to return undefined and lead to a crash. The proposed fix prevents this by adding a null check, improving the code's robustness.

Medium

@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 @smith-xyz
The issue doesn't mention pagination so I'm wondering if it's a more generic problem. Can you create few tests for that?

@smith-xyz

Copy link
Copy Markdown
Collaborator Author

Thanks @smith-xyz The issue doesn't mention pagination so I'm wondering if it's a more generic problem. Can you create few tests for that?

most certainly! I was having troubles reproducing the issue at first with the code that was provided and noticed it was specifically in relation to pagination. But maybe there is another area that needs a similar handling.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add null check for alias

Add a null check for the alias variable before accessing its metadata property
to prevent a potential runtime error if the alias is not found.

src/query-builder/SelectQueryBuilder.ts [3736-3743]

-const column =
-    alias.metadata.findColumnWithPropertyPath(
-        propertyPath,
-    ) ??
-    alias.metadata.findColumnWithDatabaseName(propertyPath)
+const column = alias
+    ? alias.metadata.findColumnWithPropertyPath(
+          propertyPath,
+      ) ??
+      alias.metadata.findColumnWithDatabaseName(propertyPath)
+    : null
 const databaseName = column
     ? column.databaseName
     : propertyPath
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential runtime error if an invalid alias is used in an orderBy clause, which would cause findAliasByName to return undefined and lead to a crash. The proposed fix prevents this by adding a null check, improving the code's robustness.

Medium
  • More

@gioboa

gioboa commented Jan 8, 2026

Copy link
Copy Markdown
Collaborator

cc @Simon3640 thanks for reporting that issue

@smith-xyz

Copy link
Copy Markdown
Collaborator Author

@gioboa added more tests to cover without pagination. This was working fine because that path has a safe check on column:

https://github.com/typeorm/typeorm/blob/master/src/query-builder/SelectQueryBuilder.ts#L2577

Hope that helps, if any other improvements are needed will gladly adjust.

@Simon3640

Copy link
Copy Markdown

your work is awesome guys ❤️ @gioboa @smith-xyz

@gioboa

gioboa commented Jan 8, 2026

Copy link
Copy Markdown
Collaborator

You can try this fix in preview with the generated package (few messages above)

@gioboa
gioboa requested review from G0maa, alumni and naorpeled January 8, 2026 21:57

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

LGTM @smith-xyz nice fix 👏

@gioboa gioboa linked an issue Jan 13, 2026 that may be closed by this pull request
@gioboa gioboa changed the title fix(query-builder): resolve column lookup when using database column name in addOrderBy with pagination fix(query-builder): resolve column lookup when using database column name in addOrderBy Jan 13, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Missing documentation for database column name support 📘 Rule violation ✓ Correctness
Description
• The PR adds support for using database column names (e.g., post.created_at) in addOrderBy,
  which is a user-facing API change
• The documentation in docs/docs/query-builder/1-select-query-builder.md only shows examples using
  property names (e.g., user.id, user.name)
• Users need to know they can now use either property names or database column names in addOrderBy
  when combined with pagination
Code

src/query-builder/SelectQueryBuilder.ts[R3740-3746]

+                        alias.metadata.findColumnWithPropertyPath(
+                            propertyPath,
+                        ) ??
+                        alias.metadata.findColumnWithDatabaseName(propertyPath)
+                    const databaseName = column
+                        ? column.databaseName
+                        : propertyPath
Evidence
The compliance checklist requires documentation updates for user-facing changes (PR Compliance ID
2). The code change adds a fallback to findColumnWithDatabaseName which allows users to pass
database column names to addOrderBy. The PR description confirms this is a user-facing change
('When using addOrderBy with a database column name'). However, searching the documentation shows no
updates to explain this new capability to users.

Rule 2: Docs updated for user-facing changes
src/query-builder/SelectQueryBuilder.ts[3740-3746]

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 PR adds support for using database column names in `addOrderBy` (e.g., `post.created_at` instead of `post.createdAt`), but this user-facing change is not documented.

## Issue Context
Users need to understand they can now use either:
- Property names: `addOrderBy("post.createdAt", "ASC")`
- Database column names: `addOrderBy("post.created_at", "ASC")`

This is especially important when working with columns that have custom database names via the `name` option in decorators like `@CreateDateColumn({ name: "created_at" })`.

## Fix Focus Areas
- docs/docs/query-builder/1-select-query-builder.md[470-506]

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



ⓘ The new review experience is currently in Beta. Learn more

Qodo Logo

@gioboa
gioboa merged commit 0ebc7e5 into typeorm:master Jan 21, 2026
38 checks passed
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.

TypeError when combining leftJoinAndSelect with addOrderBy on date fields TypeError: Cannot read property 'databaseName' of undefined

5 participants