Skip to content

fix(query-builder): guard nulls in orderBy object shorthand - #12706

Merged
alumni merged 4 commits into
typeorm:masterfrom
tsushanth:fix/orderby-nulls-undefined
Oct 21, 2026
Merged

alumni merged 4 commits into
typeorm:masterfrom
tsushanth:fix/orderby-nulls-undefined

Conversation

@tsushanth

@tsushanth tsushanth commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When orderBy is called with the object shorthand and no nulls property, the generated SQL contains a literal undefined token, producing a syntax error on all drivers.

Reproduction (SQLite):

await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .orderBy({ "post.id": { order: "ASC" } })
    .getMany();
// → SELECT ... FROM "post" "post" ORDER BY "post"."id" ASC undefined
// → QueryFailedError: near "undefined": syntax error

nulls is typed as optional in OrderByCondition, so { order: 'ASC' } is valid, but the value ends up undefined at runtime.

Root cause

SelectQueryBuilder.buildOrderByExpression (around line 2608) unconditionally concatenated:

orderBys[columnName].order + " " + orderBys[columnName].nulls

When nulls is undefined, that produces "ASC undefined".

Fix

Guard the nulls segment so it is only appended when the value is present:

orderBys[columnName].order +
    (orderBys[columnName].nulls ? " " + orderBys[columnName].nulls : "")

Reproduction confirmed on master

Tested with SQLite. The ORDER BY "post"."id" ASC undefined error is reproducible on current master and is resolved by this change.

Closes #8103

@github-actions github-actions Bot added the needs-triage PR needs issue link triage label Jul 18, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. No test for orderBy nulls ✓ Resolved
Description
The fix changes createOrderByExpression to omit the optional nulls segment, but the PR does not
add a functional regression test to ensure orderBy({ col: { order: "ASC" } }) never emits
undefined again. This risks future regressions in a user-facing SQL generation path.
Code

src/query-builder/SelectQueryBuilder.ts[R2608-2611]

                 : orderBys[columnName].order +
-                              " " +
-                              orderBys[columnName].nulls
+                              (orderBys[columnName].nulls
+                                  ? " " + orderBys[columnName].nulls
+                                  : "")
Evidence
PR Compliance ID 3 requires issue fixes to be represented in the functional test suite. The changed
SQL-building logic in SelectQueryBuilder.createOrderByExpression is the core behavior that needs a
functional regression test asserting no undefined token is produced when nulls is omitted.

Rule 3: Prefer functional tests over per-issue tests
src/query-builder/SelectQueryBuilder.ts[2605-2611]
test/functional/query-builder/order-by/query-builder-order-by.test.ts[13-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
A functional regression test is missing for the scenario where `orderBy` uses the object shorthand with `{ order: "ASC" }` and omits `nulls`, to ensure generated SQL does not contain the literal `undefined` (or an extra trailing segment).
## Issue Context
This PR changes SQL generation behavior in `SelectQueryBuilder.createOrderByExpression`. Per the compliance requirement, issue fixes should be covered in `test/functional`.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[2605-2611]
- test/functional/query-builder/order-by/query-builder-order-by.test.ts[13-120]

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



Remediation recommended

2. Incomplete nulls guard ✓ Resolved
Description
UpdateQueryBuilder.createOrderByExpression and SoftDeleteQueryBuilder.createOrderByExpression still
render " " + nulls even when nulls is omitted, producing invalid SQL like `ORDER BY x ASC
undefined`. This PR fixes the pattern only in SelectQueryBuilder, leaving other query builders with
the same runtime failure for the same valid input shape.
Code

src/query-builder/SelectQueryBuilder.ts[R2608-2611]

                 : orderBys[columnName].order +
-                              " " +
-                              orderBys[columnName].nulls
+                              (orderBys[columnName].nulls
+                                  ? " " + orderBys[columnName].nulls
+                                  : "")
Evidence
nulls is optional by type and validation, but Update/SoftDelete query builders still append it
with a leading space even when it is undefined, which in JS becomes the literal string
"undefined" in the SQL. The PR only changes SelectQueryBuilder’s concatenation, so the same bug
pattern remains in the other builders.

src/find-options/OrderByCondition.ts[11-17]
src/query-builder/QueryBuilder.ts[1730-1752]
src/query-builder/SelectQueryBuilder.ts[2597-2611]
src/query-builder/UpdateQueryBuilder.ts[768-783]
src/query-builder/SoftDeleteQueryBuilder.ts[572-586]

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

## Issue description
`nulls` is optional in `OrderByCondition`, but `UpdateQueryBuilder` and `SoftDeleteQueryBuilder` still build `ORDER BY` clauses by concatenating `nulls` unconditionally (stringifying `undefined`). This keeps the `... ASC undefined` syntax error path alive outside of `SelectQueryBuilder`.
### Issue Context
`QueryBuilder.validateOrderByCondition` explicitly allows `nulls` to be `undefined`, and `OrderByCondition` types it as optional. Therefore `{ order: "ASC" }` is valid and must not produce an `undefined` SQL token.
### Fix Focus Areas
- src/query-builder/UpdateQueryBuilder.ts[768-783]
- src/query-builder/SoftDeleteQueryBuilder.ts[572-586]
### Implementation notes
Apply the same conditional append used in `SelectQueryBuilder`:
- Build `orderValue = order + (nulls ? " " + nulls : "")`
- Or equivalently `columnName + " " + order + (nulls ? " " + nulls : "")`
Add/adjust tests (if present in this repo) to cover `.orderBy({ col: { order: "ASC" } })` for update and soft-delete builders.

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

Grey Divider

Tip of the day
💡 Did you know, you can start a comment with 'qodo' or '@qodo' to chat about any finding

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@tsushanth tsushanth changed the title fix(query-builder): guard nulls in orderBy object shorthand to avoid "ORDER BY x ASC undefined" fix(query-builder): guard nulls in orderBy object shorthand Jul 18, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 18, 2026 •

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

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

commit: e55ce65

@github-actions github-actions Bot added linked-issue PR references an issue and removed needs-triage PR needs issue link triage labels Jul 18, 2026
@tsushanth

Copy link
Copy Markdown
Contributor Author

Friendly ping — this has been approved and CI has been green for over a week. Let me know if anything is needed before merge.

@Cprakhar
Cprakhar requested a review from alumni July 29, 2026 14:34
@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

tsushanth and others added 3 commits October 21, 2026 22:33
When orderBy is called with an object like { order: 'ASC' } (no nulls
field), the generated SQL contained a literal 'undefined' token:
  ORDER BY "col" ASC undefined
causing a syntax error on all drivers.

The concatenation at buildOrderByExpression unconditionally appended
' ' + obj.nulls even when nulls was undefined.  Guard it so the
space+nulls segment is only emitted when nulls is a non-empty value.
@Cprakhar
Cprakhar force-pushed the fix/orderby-nulls-undefined branch from 44b7a83 to 1b7952b Compare October 21, 2026 17:06
@alumni
alumni merged commit da473df into typeorm:master Oct 21, 2026
46 checks passed
@github-actions github-actions Bot added this to the 2.0.next milestone Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Development

Successfully merging this pull request may close these issues.

OrderByCondition prints undefined in SQL when nulls is not provided

5 participants