Skip to content

fix: scope computed-columns join to correct table in MSSQL schema query - #12288

Merged
Cprakhar merged 6 commits into
typeorm:masterfrom
PreAgile:fix/mssql-computed-column-cross-table-join
May 9, 2026
Merged

Cprakhar merged 6 commits into
typeorm:masterfrom
PreAgile:fix/mssql-computed-column-cross-table-join

Conversation

@PreAgile

@PreAgile PreAgile commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fix the sys.computed_columns LEFT JOIN in SqlServerQueryRunner to include OBJECT_NAME and OBJECT_SCHEMA_NAME conditions
  • Without these, a regular column sharing its name with a computed column in another table was incorrectly identified as computed, generating unnecessary migrations on every sync

Root Cause

The join condition only matched by column name (COL_NAME(...) = "COLUMN_NAME"), with no table or schema filter. This caused cross-table computed column definitions to leak into unrelated tables.

Changes

  • src/driver/sqlserver/SqlServerQueryRunner.ts: Add OBJECT_NAME and OBJECT_SCHEMA_NAME conditions to the computed-columns join (2 lines)
  • New regression test: two entities (TableWithComputed, TableWithRegular) sharing column name fullName, asserting that schema diff produces no queries after initial creation

Test plan

  • pnpm tsc --noEmit passes
  • MSSQL functional test suite (CI)

Closes #12019

The LEFT JOIN on sys.computed_columns matched only by column name,
causing columns in unrelated tables to be misidentified as computed
when they shared a name with a computed column in another table.
This produced unnecessary migrations on every synchronize or
migration:generate run.

Add OBJECT_NAME and OBJECT_SCHEMA_NAME conditions to the join so
that computed column metadata is matched to the correct table and
schema.

Closes typeorm#12019
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Review Summary by Qodo

Fix MSSQL computed-column cross-table JOIN scope issue

🐞 Bug fix 🧪 Tests

Grey Divider

Walkthroughs

Description
• Fix MSSQL computed-columns JOIN to include table and schema filters
  - Prevents cross-table column name collisions from misidentifying regular columns
• Add regression test for computed column name collision scenario
  - Verifies no unnecessary migrations generated when column names match across tables
Diagram
flowchart LR
  A["MSSQL Schema Query"] -->|"Add table/schema filters"| B["Computed Columns JOIN"]
  B -->|"Correctly scoped to"| C["Specific Table & Schema"]
  D["Regression Test"] -->|"Validates"| E["No False Positives"]
  E -->|"Prevents"| F["Unnecessary Migrations"]
Loading

Grey Divider

File Changes

1. src/driver/sqlserver/SqlServerQueryRunner.ts 🐞 Bug fix +2/-0

Add table and schema filters to computed columns JOIN

• Add OBJECT_NAME condition to match computed column to correct table
• Add OBJECT_SCHEMA_NAME condition to match computed column to correct schema
• Prevents misidentification of regular columns as computed when sharing names across tables

src/driver/sqlserver/SqlServerQueryRunner.ts


2. test/functional/database-schema/generated-columns/mssql-cross-table/entity/TableWithComputed.ts 🧪 Tests +19/-0

Add test entity with computed column

• Create test entity with computed column fullName generated from firstName and lastName
• Uses STORED generated type for MSSQL computed column
• Serves as one half of cross-table name collision test scenario

test/functional/database-schema/generated-columns/mssql-cross-table/entity/TableWithComputed.ts


3. test/functional/database-schema/generated-columns/mssql-cross-table/entity/TableWithRegular.ts 🧪 Tests +10/-0

Add test entity with regular column

• Create test entity with regular column fullName (non-computed)
• Shares column name with computed column in TableWithComputed entity
• Serves as second half of cross-table name collision test scenario

test/functional/database-schema/generated-columns/mssql-cross-table/entity/TableWithRegular.ts


View more (1)
4. test/functional/database-schema/generated-columns/mssql-cross-table/generated-columns-mssql-cross-table.test.ts 🧪 Tests +33/-0

Add regression test for cross-table collision

• Add regression test for MSSQL cross-table computed column name collision
• Verifies that schema builder generates no migrations after initial creation
• Tests scenario where regular column shares name with computed column in different table
• Ensures fix prevents false positive computed column detection

test/functional/database-schema/generated-columns/mssql-cross-table/generated-columns-mssql-cross-table.test.ts


Grey Divider

Qodo Logo

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

qodo-free-for-open-source-projects Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Cross-DB COL_NAME mismatch ✓ Resolved 🐞 Bug ≡ Correctness
Description
The computed-columns join now targets "${TABLE_CATALOG}"."sys"."computed_columns", but it still uses
COL_NAME(cc.object_id, cc.column_id) which is evaluated in the current database context. When
TypeORM is asked to load tables from a non-default database (3-part names), this can prevent
computed columns from matching (or match the wrong object_id), causing incorrect schema
diffs/migrations.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R3148-3150]

+                    `LEFT JOIN "${TABLE_CATALOG}"."sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` +
+                    `AND OBJECT_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_NAME" ` +
+                    `AND OBJECT_SCHEMA_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_SCHEMA" ` +
Evidence
SqlServerDriver supports parsing 3-part names including a database, and SqlServerQueryRunner groups
tables by database and queries INFORMATION_SCHEMA per TABLE_CATALOG. In that cross-database
scenario, the join is explicitly scoped to TABLE_CATALOG for sys.computed_columns and for
OBJECT_NAME/OBJECT_SCHEMA_NAME via DB_ID(TABLE_CATALOG), but the column-name lookup still relies on
COL_NAME without any database scoping, making computed-column matching unreliable when TABLE_CATALOG
!= current database.

src/driver/sqlserver/SqlServerDriver.ts[471-558]
src/driver/sqlserver/SqlServerQueryRunner.ts[3081-3154]

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 computed-column join uses `COL_NAME(cc.object_id, cc.column_id)` while `cc` is read from a possibly different database (`"${TABLE_CATALOG}"."sys"."computed_columns"`). Because `COL_NAME` has no database parameter, cross-database table introspection can mis-detect (or fail to detect) computed columns.
## Issue Context
This code path explicitly supports querying multiple catalogs (`TABLE_CATALOG`) via `UNION ALL`. The join already adds database-scoped `OBJECT_NAME/OBJECT_SCHEMA_NAME` calls using `DB_ID(TABLE_CATALOG)`, so the remaining `COL_NAME(...) = ...` is the inconsistent piece.
## Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3146-3151]
### Implementation direction
- Replace `COL_NAME("cc"."object_id", "cc"."column_id")` with a database-independent source of the computed column name from the same rowset (e.g., join on the computed column's name field if available in the selected sys view), and keep the new table/schema scoping conditions.
- Ensure the join still works when `TABLE_CATALOG` differs from the current connection database.

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


2. Computed join wrong database ✓ Resolved 🐞 Bug ≡ Correctness
Description
In loadTables() the columns query joins to unqualified "sys"."computed_columns" while also filtering
names via DB_ID(TABLE_CATALOG), so when tables are loaded from a non-current catalog the join reads
computed columns from the connection’s current database and can miss (or mismap) computed columns
for the target catalog. This can cause computed columns to be treated as regular columns (or vice
versa), leading to incorrect schema diffs and repeated/incorrect migrations.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R3183-3185]

         `LEFT JOIN "sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` +
+                    `AND OBJECT_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_NAME" ` +
+                    `AND OBJECT_SCHEMA_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_SCHEMA" ` +
Evidence
loadTables() explicitly groups tables by TABLE_CATALOG and builds UNION ALL queries per catalog, and
other sys.* joins are catalog-qualified; however, the computed column join remains unqualified
(current DB), making computed-column detection depend on the wrong database context. Generated
column detection relies on is_persisted/definition coming from this join, so a mismatch directly
affects schema diff behavior.

src/driver/sqlserver/SqlServerQueryRunner.ts[3089-3152]
src/driver/sqlserver/SqlServerQueryRunner.ts[3171-3187]
src/driver/sqlserver/SqlServerQueryRunner.ts[3200-3211]
src/driver/sqlserver/SqlServerQueryRunner.ts[3231-3238]
src/driver/sqlserver/SqlServerQueryRunner.ts[3601-3629]

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

## Issue description
`loadTables()` builds per-catalog SQL, but the computed-column detection query joins `sys.computed_columns` without qualifying it with `TABLE_CATALOG`. On SQL Server, `sys.*` two-part names resolve in the *current database*, not the database referenced by other three-part names in the query.
### Issue Context
The PR added table/schema scoping using `OBJECT_NAME/OBJECT_SCHEMA_NAME(..., DB_ID(TABLE_CATALOG))`, but the rowset being joined still comes from the current DB’s `sys.computed_columns`, so computed columns for non-current catalogs can be missed or mismatched.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3171-3187]
### Expected fix
Update the join to reference the target catalog explicitly, e.g.:
- `LEFT JOIN "${TABLE_CATALOG}"."sys"."computed_columns" "cc" ...`
(Keep the new table/schema predicates, but ensure the `cc` rows come from the same catalog being introspected.)

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



Remediation recommended

3. Case-sensitive COLUMN_NAME bug ✓ Resolved 🐞 Bug ☼ Reliability
Description
The join compares against an unqualified "column_name" identifier even though the rest of the schema
loader expects INFORMATION_SCHEMA to provide "COLUMN_NAME". On case-sensitive SQL Server collations,
this mismatch can break the join (or the query), causing computed columns to be missed and leading
to incorrect schema diffs.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[3148]

+                    `LEFT JOIN "${TABLE_CATALOG}"."sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` +
Evidence
The query join uses the identifier "column_name", but later logic reads the result as
dbColumn["COLUMN_NAME"], indicating the expected INFORMATION_SCHEMA column key is "COLUMN_NAME";
on case-sensitive setups, this identifier mismatch can prevent correct column matching for computed
columns.

src/driver/sqlserver/SqlServerQueryRunner.ts[3145-3151]
src/driver/sqlserver/SqlServerQueryRunner.ts[3526-3574]

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 computed-column join uses `= "column_name"` instead of explicitly referencing the INFORMATION_SCHEMA column name (`"COLUMN_NAME"`). This can fail under case-sensitive collations and is also inconsistent with later code accessing `dbColumn["COLUMN_NAME"]`.
## Issue Context
The join is intended to match computed-columns rows to INFORMATION_SCHEMA.COLUMNS rows by column name.
## Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3146-3151]
### Implementation direction
- Change the join to compare against `"COLUMNS"."COLUMN_NAME"` (or at minimum `"COLUMN_NAME"`) rather than `"column_name"`.
- Keep the existing scoping conditions for `TABLE_NAME` and `TABLE_SCHEMA`.

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


4. Unescaped DB_ID literal 🐞 Bug ≡ Correctness
Description
In loadTables(), the new computed_columns join interpolates TABLE_CATALOG directly into
DB_ID('...'), so a catalog name containing a single quote will produce invalid SQL and can fail
schema introspection. This can break schema sync/migration generation for such databases.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R3183-3185]

+                    `LEFT JOIN "${TABLE_CATALOG}"."sys"."computed_columns" "cc" ON COL_NAME("cc"."object_id", "cc"."column_id") = "column_name" ` +
+                    `AND OBJECT_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_NAME" ` +
+                    `AND OBJECT_SCHEMA_NAME("cc"."object_id", DB_ID('${TABLE_CATALOG}')) = "TABLE_SCHEMA" ` +
Evidence
The modified query uses DB_ID('${TABLE_CATALOG}') without escaping, while the same file already
demonstrates that DB_ID string literals must be quote-escaped (replaceAll("'","''")) or
parameterized to avoid malformed SQL.

src/driver/sqlserver/SqlServerQueryRunner.ts[3180-3186]
src/driver/sqlserver/SqlServerQueryRunner.ts[3089-3164]
src/driver/sqlserver/SqlServerQueryRunner.ts[441-446]
src/driver/sqlserver/SqlServerQueryRunner.ts[539-562]

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

## Issue description
`loadTables()` builds a SQL string containing `DB_ID('${TABLE_CATALOG}')` in the computed-columns join. If `TABLE_CATALOG` contains a single quote (valid in SQL Server database names when bracket-escaped), the resulting SQL becomes syntactically invalid and schema introspection can fail.
### Issue Context
This file already uses safe patterns for `DB_ID(...)`:
- Parameterized: `SELECT DB_ID(@0)`
- Escaped literal: `database.replaceAll("'", "''")` before `DB_ID('...')`
The new join should follow the same approach.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3180-3186]

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


5. Missing #12019 test reference 📘 Rule violation ⚙ Maintainability
Description
The new functional regression test does not include a comment referencing the tracked issue, even
though this PR explicitly closes #12019. This reduces traceability of why the test exists and
violates the checklist expectation for issue-linked fixes.
Code

test/functional/database-schema/generated-columns/mssql-cross-table/generated-columns-mssql-cross-table.test.ts[R9-23]

+describe("database schema > generated columns > mssql cross-table computed column name collision", () => {
+    let dataSources: DataSource[]
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            enabledDrivers: ["mssql"],
+            schemaCreate: true,
+            dropSchema: true,
+        })
+    })
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should not generate migration when a regular column shares its name with a computed column in another table", () =>
+        Promise.all(
Evidence
Compliance ID 3 requires issue fixes to live in test/functional and include an issue reference
comment when applicable. The added test is in test/functional/... but contains no #12019 (or
similar) reference comment anywhere in the new file.

Rule 3: Prefer functional tests over per-issue tests
test/functional/database-schema/generated-columns/mssql-cross-table/generated-columns-mssql-cross-table.test.ts[1-33]

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 functional regression test does not include an issue reference comment (e.g., `#12019`), which is required for traceability when the fix is tied to a tracked issue.
## Issue Context
This PR states it closes `#12019`, so the new regression test should include an issue reference comment near the `describe` or `it` block.
## Fix Focus Areas
- test/functional/database-schema/generated-columns/mssql-cross-table/generated-columns-mssql-cross-table.test.ts[1-33]

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


Grey Divider

Qodo Logo

…e correctness

Also add issue reference comment to regression test for traceability.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit e94b670

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 5ecb780

@pkg-pr-new

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

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

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

commit: aa2db8a

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

@PreAgile Thanks for the amazing fix 🚀.

I just combined your test entities into the existing test suite. No need for an extra test.ts file.

@Cprakhar
Cprakhar requested review from alumni, gioboa and smith-xyz May 8, 2026 20:40
@Cprakhar
Cprakhar merged commit 36728fc into typeorm:master May 9, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone May 9, 2026
@Cprakhar Cprakhar added the backport This fix should be backported to a previous version label May 10, 2026
alumni added a commit that referenced this pull request May 16, 2026
…ry (#12288)

Co-authored-by: Piotr Kuczynski <>
Co-authored-by: Prakhar Chhalotre <[email protected]>
(cherry picked from commit 36728fc)
alumni added a commit that referenced this pull request May 18, 2026
…ry (#12288)

Co-authored-by: Piotr Kuczynski <>
Co-authored-by: Prakhar Chhalotre <[email protected]>
Co-authored-by: Lucian Mocanu <[email protected]>
(cherry picked from commit 36728fc)
@alumni alumni removed the backport This fix should be backported to a previous version label May 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

Unnecessary migrations generated with computed columns on MSSQL

5 participants