Skip to content

fix(mssql): place lock hint inside nested join parentheses (issue #12764) - #12785

Open
HosnainRafi wants to merge 1 commit into
typeorm:masterfrom
HosnainRafi:fix/12764-mssql-lock-nested-join
Open

HosnainRafi wants to merge 1 commit into
typeorm:masterfrom
HosnainRafi:fix/12764-mssql-lock-nested-join

Conversation

@HosnainRafi

@HosnainRafi HosnainRafi commented Aug 17, 2026 •

Copy link
Copy Markdown

Summary

When using lock modes (pessimistic_read, pessimistic_write, or dirty_read) with nested JOINs in MSSQL, TypeORM generates invalid SQL because the lock hint (WITH (NOLOCK), WITH (HOLDLOCK, ROWLOCK), or WITH (UPDLOCK, ROWLOCK)) is incorrectly placed after the closing parenthesis of nested joins.

Buggy Output (Before Fix)

SELECT ... FROM "post" "post" LEFT JOIN ("user" "author" LEFT JOIN "tag" "tag" ON ...) ) WITH (NOLOCK) ON ...

The lock hint appears after the closing ) of the nested join group, which is invalid MSSQL syntax.

Correct Output (After Fix)

SELECT ... FROM "post" "post" WITH (NOLOCK) LEFT JOIN ("user" "author" LEFT JOIN "tag" "tag" ON ...) ON ...

The lock hint appears immediately after the table alias, before any child joins.

Root Cause

In buildJoinClause() in SelectQueryBuilder.ts, the lock expression was appended after childJoins and the closing parenthesis (postfix), rather than before them. In MSSQL, the WITH (...) lock hint must immediately follow the table name/alias it applies to.

Fix

Moved this.createTableLockExpression() to appear after the table alias but before childJoins and postfix.

Tests

Added a new test file at test/github-issues/12764/issue-12764.test.ts with entity definitions and test cases that verify:

  • dirty_read lock places WITH (NOLOCK) correctly inside nested joins
  • pessimistic_read lock places WITH (HOLDLOCK, ROWLOCK) correctly inside nested joins
  • pessimistic_write lock places WITH (UPDLOCK, ROWLOCK) correctly inside nested joins

These tests require an MSSQL connection and will be validated by CI.

Fixes #12764

…eorm#12764)

When using lock modes (NOLOCK, HOLDLOCK, UPDLOCK) with nested JOINs
in MSSQL, the lock hint was incorrectly placed after the closing
parenthesis of nested joins, producing invalid SQL.

The lock hint must be placed immediately after the table alias,
before any child joins.

Fixes typeorm#12764
@github-actions github-actions Bot added the needs-triage PR needs issue link triage label Aug 17, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Issue test added under github-issues 📘 Rule violation ⚙ Maintainability
Description
The fix adds coverage only in test/github-issues/12764/issue-12764.test.ts instead of the
functional test suite. This violates the guideline to place issue-fix coverage in test/functional
(or clearly justify why it cannot).
Code

test/github-issues/12764/issue-12764.test.ts[R11-14]

+describe("github issues > #12764 MSSQL lock hint should be inside nested join parentheses", () => {
+    let dataSources: DataSource[]
+    before(async () => {
+        dataSources = await createTestingConnections({
Evidence
PR Compliance ID 3 requires issue fixes to add/update tests in test/functional; this PR introduces
a new test only under test/github-issues/12764, with no accompanying functional test (and no clear
rationale in the added code).

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/12764/issue-12764.test.ts[11-17]

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

## Issue description
This PR adds an issue-specific test under `test/github-issues`, but the compliance checklist requires issue fixes to be covered by the functional test suite (`test/functional`) unless there is a clear reason.

## Issue Context
The new test file is located at `test/github-issues/12764/issue-12764.test.ts` and validates MSSQL lock-hint placement for nested joins.

## Fix Focus Areas
- test/github-issues/12764/issue-12764.test.ts[11-17]

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


2. Test misses nested join 🐞 Bug ☼ Reliability
Description
issue-12764.test.ts does not create a join with child joins (nested join group), so the SQL path
that previously produced ) WITH (...) is never exercised and the assertions will pass even on the
pre-fix implementation. This makes the new test ineffective at validating the fix in buildJoinClause
for nested join parentheses.
Code

test/github-issues/12764/issue-12764.test.ts[R25-28]

+                .createQueryBuilder(Post, "post")
+                .setLock("dirty_read")
+                .leftJoinAndSelect("post.author", "author")
+                .leftJoinAndSelect("post.tag", "tag")
Evidence
The join-tree builder only nests joins when it finds an existing parent alias in mappedTrees, and
parentheses in buildJoinClause() are only added when childJoins is non-empty. The test query
only joins from post.*, so it creates sibling joins (no children), meaning no (...) join group
is generated and the bug path (postfix + lockHint) is not exercised.

test/github-issues/12764/issue-12764.test.ts[22-38]
src/query-builder/SelectQueryBuilder.ts[2333-2360]
src/query-builder/SelectQueryBuilder.ts[2381-2386]
src/query-builder/SelectQueryBuilder.ts[2562-2571]

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 new test cases claim to validate lock-hint placement for *nested* joins, but the query only joins two relations directly from the root alias (`post.author` and `post.tag`). This produces sibling joins, not a nested join group, so `childJoins` is empty and `buildJoinClause()` never emits the parenthesized form that previously placed `WITH (...)` after the closing `)`.

## Issue Context
`buildJoinClause()` only adds parentheses when `childJoins` is non-empty. Join nesting happens only when a join has another join as its parent alias (e.g. joining `author.posts` after joining `post.author`).

## Fix Focus Areas
- test/github-issues/12764/issue-12764.test.ts[22-66]
- src/query-builder/SelectQueryBuilder.ts[2333-2360]
- src/query-builder/SelectQueryBuilder.ts[2381-2386]
- src/query-builder/SelectQueryBuilder.ts[2562-2583]

## Suggested fix
1. Update each test query to actually produce a nested join group, e.g.:
  - `.leftJoinAndSelect("post.author", "author")`
  - `.leftJoinAndSelect("author.posts", "authorPosts")`  // creates a child join under `author`
  (You already have `User.posts` and `Post.author`, so this should be feasible with existing entities.)
2. Update assertions to target the *nested* join group behavior, e.g. ensure:
  - it **does not** contain `) WITH (NOLOCK)` / `) WITH (HOLDLOCK, ROWLOCK)` / `) WITH (UPDLOCK, ROWLOCK)`
  - it **does** contain something like `JOIN ("user" "author" WITH (...)` (or a regex that tolerates schema prefixes) to prove the hint is inside the parenthesized join group.

ⓘ 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.
Tip of the day
💡 Did you know, you can route each action level your way: inline, summary, both, or drop

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@github-actions github-actions Bot added linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR and removed needs-triage PR needs issue link triage labels Aug 26, 2026
@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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Compliance violation linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR

Development

Successfully merging this pull request may close these issues.

MSSQL: lock table hint emitted outside nested join parentheses, producing invalid SQL (1.1.0 regression)

2 participants