Skip to content

fix: compare entity ids of mixed string/number type as equal - #12780

Open
Arul1998 wants to merge 7 commits into
typeorm:masterfrom
Arul1998:fix/compare-ids-bigint-string
Open

Arul1998 wants to merge 7 commits into
typeorm:masterfrom
Arul1998:fix/compare-ids-bigint-string

Conversation

@Arul1998

@Arul1998 Arul1998 commented Aug 12, 2026 •

Copy link
Copy Markdown

Description of change

What this does: Makes OrmUtils.compareIds treat a single-id map as equal
when the two ids hold the same value but different primitive types — e.g. "1"
(string) and 1 (number), including scaled decimals like "70.000" and 70.

Why it's needed: compareIds only short-circuited when both ids shared the
same primitive type (both string or both number). Drivers such as MySQL/MariaDB
return bigint columns as strings (bigNumberStrings defaults to true), so a
persisted id can be "1" on the DB-loaded side and 1 in memory. That mismatched
pair matched no branch and fell through to false (deepCompare → compare2Objects
also only string-normalizes same-type primitives). As a result
OneToManySubjectBuilder saw the child as orphaned and, under the default
orphanedRowAction: "nullify", nulled its FK on save — erroring when the FK is
NOT NULL. This is why int PKs are unaffected (both sides are numbers) but
bigint PKs break (#11773).

The change: In the single-id fast path, when the two id types differ, compare
by numeric value rather than string form, so "1" matches 1 and a scaled
decimal "70.000" matches 70. Guards keep it safe:

  • NaN / Infinity never match.
  • Integers beyond Number.MAX_SAFE_INTEGER never match, so a rounded JS number
    can't collide with a different bigint string.
  • The string side must be a plain decimal numeral, so permissive Number() forms
    ("" → 0, "0x10" → 16, "1e2" → 100) can't coerce distinct keys together.

Same-type comparisons are unchanged (still firstId.id === secondId.id), and the
general-purpose compare2Objects is left untouched to avoid affecting jsonb/object
diffing elsewhere.

How it was verified:

  • Unit tests (test/unit/util/orm-utils.test.ts) for compareIds: same-type
    equality, string-vs-number equality ("1" === 1), decimals incl. scale
    ("70.000" === 70), unequal string/number staying false, null/undefined
    handling, NaN/Infinity rejection, unsafe-integer rejection, permissive
    numeric-string rejection, and the composite-id deepCompare fallback — all
    passing.
  • A functional regression test (test/github-issues/11773, mysql/mariadb) with an
    int parent PK and a bigint child PK. On re-save the parent always matches, so
    the test can only fail the way Automated cascade sets FK to NULL for bigint relations when saving parent entity (MySQL) #11773 actually failed — the child's bigint id is
    1 in memory and "1" from the driver — and asserts the child's FK survives.

Notes for maintainers:

  • Composite / non-id primary keys still route through deepCompare and are out of
    scope for this narrow, single-column fix.
  • The numeric compare deliberately does not attempt full decimal canonicalization
    (e.g. "0.10000000000000001" vs 0.1); that is IEEE-754 Number() behavior,
    unrealistic for a real bigint/int/fixed-scale decimal primary key, and out of
    scope here. Happy to take a driver-level normalization direction instead if you'd
    prefer solving the whole coercion class.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword:
    Fixes #11773
  • There are new or updated tests validating the change
    (test/unit/util/orm-utils.test.ts, test/github-issues/11773)
  • Documentation has been updated to reflect this change (docs/docs/**.md) — N/A (internal comparison fix, no public API/doc change)

@github-actions github-actions Bot added the linked-issue PR references an issue label Aug 12, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Distinct keys are treated as one entity ⊘ Outdated 🐞 Bug ≡ Correctness
Description
compareIds converts every mixed string/number pair with Number(), which rounds exact decimal
text such as "0.10000000000000001" to 0.1 and also parses forms such as "0x10" or an empty
string. When a decimal key exceeds binary fractional precision or a string primary key has one of
these forms, persistence matching treats separate identifiers as equal and can skip relation updates
or junction changes.
Code

src/util/OrmUtils.ts[R261-263]

+            const stringAsNumber = Number(
+                typeof firstId.id === "string" ? firstId.id : secondId.id,
+            )
Evidence
The new path converts the textual identifier to a number, guards only non-finite values and unsafe
integers, and then compares numeric values, leaving fractional rounding and permissive numeric
syntax unchecked. Decimal identifiers are explicitly supported by the added tests, identifier maps
preserve primary-column values, and persistence consumers use equality to suppress relation updates
and junction-table operations.

src/util/OrmUtils.ts[259-272]
test/unit/util/orm-utils.test.ts[309-320]
src/metadata/EntityMetadata.ts[653-659]
src/persistence/SubjectChangedColumnsComputer.ts[272-285]
src/persistence/subject-builder/ManyToManySubjectBuilder.ts[166-178]
src/persistence/subject-builder/ManyToManySubjectBuilder.ts[237-248]

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

## Issue description
Mixed string/number identifiers are converted through `Number()`, which loses fractional decimal precision and accepts empty or radix-prefixed strings, allowing distinct identifiers to compare equal.
## Fix Focus Areas
- src/util/OrmUtils.ts[254-272]
- test/unit/util/orm-utils.test.ts[309-382]
## Recommended Fix
Validate the string operand against a strict decimal syntax and compare exact canonical decimal representations rather than converting it to an IEEE-754 number. Normalize signs, exponents, leading zeros, and insignificant fractional zeros so cases such as `"70.000"` and `70` remain equal, while adding regression tests ensuring `"0.10000000000000001"` differs from `0.1` and empty, whitespace, or radix-prefixed strings do not match numbers.

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


2. Identifier checks carry excess narration ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
compareIds adds an eleven-line comment that narrates each straightforward finite-number and
safe-integer check, including examples and the historical failure mode. When the comparison rules
change, maintainers must reconcile this embedded explanation with both the executable guards and
their dedicated tests.
Code

src/util/OrmUtils.ts[R254-257]

+            // Types differ (one string, one number): bridge the driver's
+            // number->string coercion, but only when String(number) can be
+            // trusted to represent the value faithfully:
+            //   - NaN and Infinity are never valid ids.
Evidence
Compliance rule 4 prohibits extra AI-like comments and style inconsistent with the surrounding file.
The added block at src/util/OrmUtils.ts[254-264] extensively narrates the immediately following
finite-number and safe-integer guards rather than limiting itself to the non-obvious rationale.

Rule 4: Remove AI-generated noise
src/util/OrmUtils.ts[254-264]

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 mixed-type identifier guard is preceded by an oversized comment that repeats behavior already expressed by the checks and covered by tests.
## Fix Focus Areas
- src/util/OrmUtils.ts[254-264]
## Recommended Fix
Replace the multi-line narration with one concise comment explaining only the non-obvious precision reason for rejecting unsafe integers, leaving examples and behavioral detail in the tests.

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


3. Scaled decimal IDs remain unmatched ✓ Resolved 🐞 Bug ≡ Correctness
Description
compareIds uses JavaScript string equality for mixed values, so a numeric 70 does not match an
equivalent hydrated decimal identifier such as "70.000" despite the new comments claiming finite
decimals stringify faithfully. Drivers preserve declared decimal scale, and this comparator feeds
persistence relation differences, so scaled decimal primary keys can still be classified as
different entities.
Code

src/util/OrmUtils.ts[R267-270]

+            if (!Number.isFinite(numericId)) return false
+            if (Number.isInteger(numericId) && !Number.isSafeInteger(numericId))
+                return false
+            return String(firstId.id) === String(secondId.id)
Evidence
The new branch compares only String(firstId.id) === String(secondId.id). Existing database tests
demonstrate that decimal values retain scale through persistence and hydration ("70.000" remains
unchanged), while MySQL entity definitions also model decimal and numeric columns as strings.

src/util/OrmUtils.ts[254-270]
test/functional/database-schema/column-types/sap/column-types-sap.test.ts[182-202]
test/functional/database-schema/column-types/sap/column-types-sap.test.ts[210-220]
test/functional/database-schema/column-types/mysql/entity/Post.ts[48-55]
src/persistence/subject-builder/OneToManySubjectBuilder.ts[137-154]

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

## Issue description
Mixed string and number identifiers are compared using their JavaScript string forms, which rejects numerically equivalent decimal representations such as `70` and `"70.000"`.
## Fix Focus Areas
- src/util/OrmUtils.ts[254-270]
- test/unit/util/orm-utils.test.ts[309-322]
## Recommended Fix
Canonicalize valid decimal syntax on both sides before comparison, including scale and exponent notation, without converting arbitrary database strings through `Number` and losing bigint precision. Add cases for trailing zeros and exponent-versus-fixed notation while retaining the non-finite and unsafe-integer protections.

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


View action required (2)
4. Test comments narrate obvious steps ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
issue-11773.test.ts labels the immediately following object construction as seeding a parent and
later labels the direct parentId assertion as the regression, although both are already expressed
by the test name and statements. These redundant annotations add a second narrative that later edits
must keep synchronized with the executable scenario.
Code

test/github-issues/11773/issue-11773.test.ts[36]

+                // Seed a parent with one child (cascade insert).
Evidence
Compliance rule 4 prohibits extra comments and AI-like noise. The cited comments only label
straightforward setup and assertion statements, rather than documenting behavior that cannot be
inferred from the test.

Rule 4: Remove AI-generated noise
test/github-issues/11773/issue-11773.test.ts[36-36]
test/github-issues/11773/issue-11773.test.ts[58-58]

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 regression test contains comments that merely narrate the immediately following setup and assertion, adding maintenance noise without explaining non-obvious behavior.
## Fix Focus Areas
- test/github-issues/11773/issue-11773.test.ts[36-36]
- test/github-issues/11773/issue-11773.test.ts[58-58]
## Recommended Fix
Remove the redundant seed and regression-label comments while retaining the driver-specific explanation that documents why the mixed identifier types occur.

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


5. Null tests bypass type checking ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The compareIds tests pass explicit null values through six as any casts instead of
representing the supported value in the method's parameter types. When these cases compile, the
casts suppress contract checking and allow the runtime null handling and declared input types to
drift apart.
Code

test/unit/util/orm-utils.test.ts[R319-321]

+            expect(OrmUtils.compareIds(null as any, { id: 1 })).to.equal(false)
+            expect(OrmUtils.compareIds({ id: 1 }, null as any)).to.equal(false)
+            expect(OrmUtils.compareIds(null as any, null as any)).to.equal(
Evidence
Compliance rule 4 explicitly prohibits any-casts used to bypass type issues. The added tests cast
null to any, while compareIds already contains explicit runtime branches for null but omits null
from its declared parameter types.

Rule 4: Remove AI-generated noise
test/unit/util/orm-utils.test.ts[319-323]
src/util/OrmUtils.ts[225-233]

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 null-handling tests use `as any`, bypassing type checking even though `compareIds` explicitly handles null values at runtime.
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[319-323]
- src/util/OrmUtils.ts[225-233]
## Recommended Fix
Add `null` to both `compareIds` parameter types, then remove every `as any` cast from the null-input assertions.

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



Remediation recommended

6. The regression test fails too early ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The fixture declares Parent.id as bigint and reconstructs it as a number, so without the fix the
subject loader cannot match the hydrated string parent and treats that parent as insertable instead
of loading its existing relations. A duplicate-parent insertion can therefore fail before the
one-to-many orphan comparison, meaning the test does not isolate the child foreign-key regression it
claims to exercise.
Code

test/github-issues/11773/entity/Parent.ts[R6-7]

+    @PrimaryColumn({ type: "bigint" })
+    id: number
Evidence
MySQL hydration leaves explicit bigint columns as strings, and loaded rows are assigned to save
subjects through compareIds. When that parent match fails, mustBeInserted becomes true and the
one-to-many builder has no parent database entity from which to obtain existing relation IDs.

test/github-issues/11773/entity/Parent.ts[4-10]
test/github-issues/11773/issue-11773.test.ts[48-53]
src/driver/mysql/MysqlDriver.ts[671-738]
src/persistence/SubjectDatabaseEntityLoader.ts[129-139]
src/persistence/Subject.ts[178-185]
src/persistence/subject-builder/OneToManySubjectBuilder.ts[71-82]

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 regression fixture gives both parent and child bigint identifiers, allowing parent database-entity matching to fail before the intended child relation comparison runs.
## Fix Focus Areas
- test/github-issues/11773/entity/Parent.ts[6-7]
- test/github-issues/11773/issue-11773.test.ts[48-53]
## Recommended Fix
Use a normal numeric primary column for the parent while retaining the bigint child primary key. This ensures the parent is loaded successfully under the old behavior and the test fails specifically because the child identifier is incorrectly classified as removed.

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


7. Decimal identifiers still mismatch ✓ Resolved 🐞 Bug ≡ Correctness
Description
compareIds rejects every mixed-type pair whose numeric side is fractional because
Number.isSafeInteger is false even for finite values such as 1.5. A valid decimal primary key
loaded as "1.5" and represented in memory as 1.5 therefore remains unequal, so persistence
diffing can treat the same row or relation as removed.
Code

src/util/OrmUtils.ts[264]

+            if (!Number.isSafeInteger(numericId)) return false
Evidence
Primary columns accept general column types, including decimal and numeric types, while repository
integration tests deliberately model MySQL decimal values as strings and verify that they remain
strings after loading. Identifier maps preserve primary-column values, so a decimal key represented
as a number in memory can reach this new branch opposite its string-valued loaded form, where the
added safe-integer check rejects it.

src/decorator/columns/PrimaryColumn.ts[32-47]
src/driver/types/ColumnTypes.ts[14-19]
test/functional/database-schema/column-types/mysql/entity/Post.ts[48-55]
test/functional/database-schema/column-types/mysql/column-types-mysql.test.ts[95-111]
src/metadata/EntityMetadata.ts[973-985]

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 mixed string/number identifier path rejects finite fractional numbers because it requires `Number.isSafeInteger`, even though decimal and numeric columns can be primary keys and drivers represent these values as strings.
## Fix Focus Areas
- src/util/OrmUtils.ts[262-265]
- test/unit/util/orm-utils.test.ts[324-364]
## Recommended Fix
Reject non-finite numbers and unsafe integral numbers, but permit finite fractional numbers to reach the canonical string comparison. Add tests in both argument orders for an equivalent pair such as `"1.5"` and `1.5`, while retaining the existing non-finite and unsafe-integer coverage.

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


8. Unsafe integer id coercion ✓ Resolved 🐞 Bug ≡ Correctness
Description
In OrmUtils.compareIds, the mixed string/number fast-path compares ids via String(...) for any
finite number; for numbers > Number.MAX_SAFE_INTEGER this can silently match the wrong database id
due to IEEE-754 rounding. Because compareIds is used to match loaded entities/relations (e.g.,
SubjectDatabaseEntityLoader and OneToManySubjectBuilder), an incorrect equality can associate
changes with the wrong row.
Code

src/util/OrmUtils.ts[R254-257]

+            const numericId =
+                typeof firstId.id === "number" ? firstId.id : secondId.id
+            if (!Number.isFinite(numericId)) return false
+            return String(firstId.id) === String(secondId.id)
Evidence
The new cross-type path only rejects non-finite numbers, then compares by stringification, which is
unsafe for integers beyond JS’s safe range. compareIds is used in persistence matching/diffing
paths, so a false positive equality can mis-associate entities/relations.

src/util/OrmUtils.ts[233-258]
src/persistence/SubjectDatabaseEntityLoader.ts[133-139]
src/persistence/subject-builder/OneToManySubjectBuilder.ts[137-146]

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

## Issue description
`OrmUtils.compareIds` now bridges `string` vs `number` ids by comparing `String(firstId.id) === String(secondId.id)` after only `Number.isFinite(...)`. If the numeric id is outside JS safe-integer range, `String(number)` can reflect a *rounded* value, which can incorrectly match a different bigint id string.
### Issue Context
This function is used in persistence logic to decide whether two identifiers refer to the same row.
### Fix Focus Areas
- src/util/OrmUtils.ts[239-258]
### Suggested fix
- In the mixed-type branch, add a guard requiring `Number.isSafeInteger(numericId)` (and implicitly integer-ness) before doing `String(...)` equality. If it’s not a safe integer, return `false` (forcing callers to use consistent types such as strings/native bigint for large ids).
- Add a unit test to `test/unit/util/orm-utils.test.ts` asserting that an unsafe integer (e.g. `9007199254740993`) does **not** cross-type match a string id.

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


View review recommended (3)
9. NaN/Infinity id collision ✓ Resolved 🐞 Bug ≡ Correctness
Description
OrmUtils.compareIds now stringifies mixed string/number ids, which makes { id: NaN } equal to `{
id: "NaN" } (and similarly for ±Infinity`). This can cause identifier collisions in
persistence-diffing paths that rely on compareIds to decide whether two relations/subjects refer
to the same row.
Code

src/util/OrmUtils.ts[R247-249]

+            return typeof firstId.id === typeof secondId.id
+                ? firstId.id === secondId.id
+                : String(firstId.id) === String(secondId.id)
Evidence
The new fast path explicitly string-compares mixed string/number ids, which makes String(NaN)
become "NaN" and String(Infinity) become "Infinity", enabling cross-type equality that
previously could not happen. deepCompare/compare2Objects only special-cases NaN when both sides
are NaN and otherwise rejects mixed primitive types, so this cross-type equality is new and can
affect persistence logic that uses compareIds for relation/id matching.

src/util/OrmUtils.ts[233-250]
src/util/OrmUtils.ts[454-491]
src/persistence/SubjectChangedColumnsComputer.ts[247-286]

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

## Issue description
`OrmUtils.compareIds` treats mixed `{ id: number }` vs `{ id: string }` as equal by comparing their `String(...)` forms. This introduces a regression where invalid numeric ids (`NaN`, `Infinity`, `-Infinity`) become equal to the literal strings `"NaN"`, `"Infinity"`, and `"-Infinity"`.
### Issue Context
`compareIds` is used in persistence diffing (e.g., relation change detection). Allowing non-finite numbers to collide with string ids can make unrelated entities appear identical.
### Fix
Inside the single-`id` fast path, before doing the cross-type `String(...) === String(...)` comparison, guard against non-finite numbers:
- If either side is a `number` and `!Number.isFinite(value)`, return `false` (or skip the fast path and fall back).
Add unit tests asserting:
- `compareIds({id: NaN}, {id: "NaN"}) === false`
- `compareIds({id: Infinity}, {id: "Infinity"}) === false`
### Fix Focus Areas
- src/util/OrmUtils.ts[239-250]
- test/unit/util/orm-utils.test.ts[274-313]

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


10. Issue #11773 only unit-tested ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
This PR adds regression coverage for #11773 only in test/unit, but the checklist expects issue-fix
coverage to live in test/functional to exercise real persistence behavior across drivers. Relying
solely on unit tests may miss integration regressions in relation handling (the original reported
failure mode).
Code

test/unit/util/orm-utils.test.ts[R284-288]

+        it("matches a string id against a numeric id when their values are equal", () => {
+            // MySQL and some other drivers return bigint columns as strings, so
+            // the DB-loaded id ("1") and the in-memory id (1) must still compare
+            // as equal — otherwise the relation looks removed and its FK is nulled
+            // (see #11773).
Evidence
PR Compliance ID 3 calls for issue fixes to be validated in the functional test suite. The added
regression coverage for compareIds (including a see #11773 note) is located under test/unit,
indicating the issue fix is not validated via a functional persistence scenario.

Rule 3: Prefer functional tests over per-issue tests
test/unit/util/orm-utils.test.ts[284-292]

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 regression for #11773 is currently covered only by a unit test (`describe("compareIds" ...)`) rather than a functional/integration test.
## Issue Context
PR Compliance ID 3 requires issue fixes to be validated in the functional suite (`test/functional`) so the behavior is exercised through real persistence flows and driver-specific type behavior (e.g., MySQL bigint ids as strings).
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[274-313]
- test/functional/relations/orphaned-row-action/orphaned-row-action.test.ts[1-120]

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


11. NaN id coerces equal ✓ Resolved 🐞 Bug ≡ Correctness
Description
OrmUtils.compareIds now stringifies mixed string/number ids, which makes { id: NaN } compare
equal to { id: "NaN" } (and similarly for Infinity), potentially treating invalid/uninitialized
identifiers as the same entity during persistence diffing.
Code

src/util/OrmUtils.ts[R247-250]

+            return typeof firstId.id === typeof secondId.id
+                ? firstId.id === secondId.id
+                : String(firstId.id) === String(secondId.id)
}
Evidence
The new mixed-type branch compares ids via String(...), which makes NaN/Infinity comparable to
their string literals. compare2Objects already treats NaN as a special case, suggesting that NaN
semantics matter and should not be accidentally broadened for ids.

src/util/OrmUtils.ts[221-252]
src/util/OrmUtils.ts[446-489]

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

## Issue description
`OrmUtils.compareIds` falls back to `String(firstId.id) === String(secondId.id)` when one side is a `number` and the other is a `string`. This unintentionally allows non-finite numbers (e.g. `NaN`, `Infinity`) to compare equal to their string spellings ("NaN", "Infinity"), which can cause incorrect id equality results.
### Issue Context
Elsewhere in `OrmUtils` there is explicit NaN-handling in `compare2Objects`, indicating that special numeric values need deliberate treatment rather than accidental equality via stringification.
### Fix Focus Areas
- src/util/OrmUtils.ts[233-252]
### Suggested change
Before applying the mixed-type string comparison, guard against non-finite numeric values:
- If `typeof firstId.id === "number"` and `!Number.isFinite(firstId.id)`, return `false`.
- If `typeof secondId.id === "number"` and `!Number.isFinite(secondId.id)`, return `false`.
(Optionally also consider requiring integers for the numeric side if ids are expected to be integral.)

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



Informational

12. A comment wrongly excludes decimals ⊘ Outdated 🐞 Bug ⚙ Maintainability
Description
compareIds says the mixed-type path requires a safe integer, while its implementation only rejects
integers outside the safe range and deliberately accepts fractional values. The new
decimal-identifier tests establish 1.5 and scaled 70.000 as supported, so a later maintainer
following the comment could remove intended behavior.
Code

src/util/OrmUtils.ts[R254-255]

+            // Types differ (one string, one number): compare by numeric value,
+            // requiring a plain decimal numeral and a safe integer (see #11773).
Evidence
The implementation applies Number.isSafeInteger only when each converted value is an integer,
while the added tests explicitly require fractional and scaled decimal identifiers to compare equal.

src/util/OrmUtils.ts[254-269]
test/unit/util/orm-utils.test.ts[309-321]

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 mixed-type identifier comparison comment says values must be safe integers, but the implementation and tests intentionally support finite decimal values. This misleading description could cause future changes to reject supported decimal identifiers.
## Fix Focus Areas
- src/util/OrmUtils.ts[254-255]
## Recommended Fix
Update the comment to state that the path requires a plain decimal numeral and rejects unsafe integer representations, while finite fractional values remain supported.

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


13. Null handling untested ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
The new compareIds test claims to cover null and undefined inputs, but it only asserts undefined
cases, so regressions in the explicit null handling path would not be caught.
Code

test/unit/util/orm-utils.test.ts[R299-303]

+        it("returns false when either id map is null or undefined", () => {
+            expect(OrmUtils.compareIds(undefined, { id: 1 })).to.equal(false)
+            expect(OrmUtils.compareIds({ id: 1 }, undefined)).to.equal(false)
+            expect(OrmUtils.compareIds(undefined, undefined)).to.equal(false)
+        })
Evidence
The test block title mentions null, but the assertions only pass undefined. The production code
explicitly checks for both undefined and null, so the null branch remains unexercised by this
new test.

test/unit/util/orm-utils.test.ts[274-313]
src/util/OrmUtils.ts[221-232]

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 `compareIds` test case says it covers "null or undefined" inputs but only tests `undefined`. This reduces regression coverage for the implementation’s explicit `null` checks.
### Issue Context
`OrmUtils.compareIds` returns `false` when either input is `null` or `undefined`.
### Fix Focus Areas
- test/unit/util/orm-utils.test.ts[299-303]
### Suggested change
Extend the test to include:
- `OrmUtils.compareIds(null as any, { id: 1 }) === false`
- `OrmUtils.compareIds({ id: 1 }, null as any) === false`
- `OrmUtils.compareIds(null as any, null as any) === false`
Or, if you prefer, rename the test title to mention only `undefined` if that’s the intended coverage.

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


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
Review mode: ⚖️ Balanced: This changes core ORM identifier matching and persistence relation diffing across multiple drivers, with meaningful data-integrity risk despite focused logic and extensive tests.

Grey Divider

Tip of the day
💡 Did you know, you can type 'qodo, fix this' on a finding and the fix lands right on your PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Issue #11773 only unit-tested 📘 Rule violation ⚙ Maintainability ⭐ New
Description
This PR adds regression coverage for #11773 only in test/unit, but the checklist expects issue-fix
coverage to live in test/functional to exercise real persistence behavior across drivers. Relying
solely on unit tests may miss integration regressions in relation handling (the original reported
failure mode).
Code

test/unit/util/orm-utils.test.ts[R284-288]

+        it("matches a string id against a numeric id when their values are equal", () => {
+            // MySQL and some other drivers return bigint columns as strings, so
+            // the DB-loaded id ("1") and the in-memory id (1) must still compare
+            // as equal — otherwise the relation looks removed and its FK is nulled
+            // (see #11773).
Evidence
PR Compliance ID 3 calls for issue fixes to be validated in the functional test suite. The added
regression coverage for compareIds (including a see #11773 note) is located under test/unit,
indicating the issue fix is not validated via a functional persistence scenario.

Rule 3: Prefer functional tests over per-issue tests
test/unit/util/orm-utils.test.ts[284-292]

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 regression for #11773 is currently covered only by a unit test (`describe("compareIds" ...)`) rather than a functional/integration test.

## Issue Context
PR Compliance ID 3 requires issue fixes to be validated in the functional suite (`test/functional`) so the behavior is exercised through real persistence flows and driver-specific type behavior (e.g., MySQL bigint ids as strings).

## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[274-313]
- test/functional/relations/orphaned-row-action/orphaned-row-action.test.ts[1-120]

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


2. NaN id coerces equal 🐞 Bug ≡ Correctness ⭐ New
Description
OrmUtils.compareIds now stringifies mixed string/number ids, which makes { id: NaN } compare
equal to { id: "NaN" } (and similarly for Infinity), potentially treating invalid/uninitialized
identifiers as the same entity during persistence diffing.
Code

src/util/OrmUtils.ts[R247-250]

+            return typeof firstId.id === typeof secondId.id
+                ? firstId.id === secondId.id
+                : String(firstId.id) === String(secondId.id)
        }
Evidence
The new mixed-type branch compares ids via String(...), which makes NaN/Infinity comparable to
their string literals. compare2Objects already treats NaN as a special case, suggesting that NaN
semantics matter and should not be accidentally broadened for ids.

src/util/OrmUtils.ts[221-252]
src/util/OrmUtils.ts[446-489]

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

### Issue description
`OrmUtils.compareIds` falls back to `String(firstId.id) === String(secondId.id)` when one side is a `number` and the other is a `string`. This unintentionally allows non-finite numbers (e.g. `NaN`, `Infinity`) to compare equal to their string spellings ("NaN", "Infinity"), which can cause incorrect id equality results.

### Issue Context
Elsewhere in `OrmUtils` there is explicit NaN-handling in `compare2Objects`, indicating that special numeric values need deliberate treatment rather than accidental equality via stringification.

### Fix Focus Areas
- src/util/OrmUtils.ts[233-252]

### Suggested change
Before applying the mixed-type string comparison, guard against non-finite numeric values:
- If `typeof firstId.id === "number"` and `!Number.isFinite(firstId.id)`, return `false`.
- If `typeof secondId.id === "number"` and `!Number.isFinite(secondId.id)`, return `false`.

(Optionally also consider requiring integers for the numeric side if ids are expected to be integral.)

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


3. NaN/Infinity id collision 🐞 Bug ≡ Correctness
Description
OrmUtils.compareIds now stringifies mixed string/number ids, which makes { id: NaN } equal to `{
id: "NaN" } (and similarly for ±Infinity`). This can cause identifier collisions in
persistence-diffing paths that rely on compareIds to decide whether two relations/subjects refer
to the same row.
Code

src/util/OrmUtils.ts[R247-249]

+            return typeof firstId.id === typeof secondId.id
+                ? firstId.id === secondId.id
+                : String(firstId.id) === String(secondId.id)
Evidence
The new fast path explicitly string-compares mixed string/number ids, which makes String(NaN)
become "NaN" and String(Infinity) become "Infinity", enabling cross-type equality that
previously could not happen. deepCompare/compare2Objects only special-cases NaN when both sides
are NaN and otherwise rejects mixed primitive types, so this cross-type equality is new and can
affect persistence logic that uses compareIds for relation/id matching.

src/util/OrmUtils.ts[233-250]
src/util/OrmUtils.ts[454-491]
src/persistence/SubjectChangedColumnsComputer.ts[247-286]

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

## Issue description
`OrmUtils.compareIds` treats mixed `{ id: number }` vs `{ id: string }` as equal by comparing their `String(...)` forms. This introduces a regression where invalid numeric ids (`NaN`, `Infinity`, `-Infinity`) become equal to the literal strings `"NaN"`, `"Infinity"`, and `"-Infinity"`.
### Issue Context
`compareIds` is used in persistence diffing (e.g., relation change detection). Allowing non-finite numbers to collide with string ids can make unrelated entities appear identical.
### Fix
Inside the single-`id` fast path, before doing the cross-type `String(...) === String(...)` comparison, guard against non-finite numbers:
- If either side is a `number` and `!Number.isFinite(value)`, return `false` (or skip the fast path and fall back).
Add unit tests asserting:
- `compareIds({id: NaN}, {id: "NaN"}) === false`
- `compareIds({id: Infinity}, {id: "Infinity"}) === false`
### Fix Focus Areas
- src/util/OrmUtils.ts[239-250]
- test/unit/util/orm-utils.test.ts[274-313]

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



Informational

4. Null handling untested 🐞 Bug ⚙ Maintainability ⭐ New
Description
The new compareIds test claims to cover null and undefined inputs, but it only asserts undefined
cases, so regressions in the explicit null handling path would not be caught.
Code

test/unit/util/orm-utils.test.ts[R299-303]

+        it("returns false when either id map is null or undefined", () => {
+            expect(OrmUtils.compareIds(undefined, { id: 1 })).to.equal(false)
+            expect(OrmUtils.compareIds({ id: 1 }, undefined)).to.equal(false)
+            expect(OrmUtils.compareIds(undefined, undefined)).to.equal(false)
+        })
Evidence
The test block title mentions null, but the assertions only pass undefined. The production code
explicitly checks for both undefined and null, so the null branch remains unexercised by this
new test.

test/unit/util/orm-utils.test.ts[274-313]
src/util/OrmUtils.ts[221-232]

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 `compareIds` test case says it covers "null or undefined" inputs but only tests `undefined`. This reduces regression coverage for the implementation’s explicit `null` checks.

### Issue Context
`OrmUtils.compareIds` returns `false` when either input is `null` or `undefined`.

### Fix Focus Areas
- test/unit/util/orm-utils.test.ts[299-303]

### Suggested change
Extend the test to include:
- `OrmUtils.compareIds(null as any, { id: 1 }) === false`
- `OrmUtils.compareIds({ id: 1 }, null as any) === false`
- `OrmUtils.compareIds(null as any, null as any) === false`

Or, if you prefer, rename the test title to mention only `undefined` if that’s the intended coverage.

ⓘ 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 enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

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

qodo-free-for-open-source-projects Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

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

OrmUtils.compareIds only short-circuited when both ids shared the same
primitive type (both string or both number). Drivers such as MySQL return
bigint columns as strings, so a persisted id can be "1" on the DB-loaded
side and 1 in memory. The mismatched pair matched no branch and fell
through to a false result, making the relation look removed and nulling
its FK on save.

Compare single-id maps by their string form when the two types differ, so
"1" still matches 1. Same-type comparisons are unchanged.

Fixes typeorm#11773
Guard the string/number id path so NaN and Infinity are not coerced to
match a "NaN"/"Infinity" string. Add unit tests for the non-finite and
null id cases.
…teger

Address review feedback on the mixed string/number entity-id comparison
in OrmUtils.compareIds (typeorm#11773). Beyond Number.MAX_SAFE_INTEGER a JS
number cannot represent a bigint exactly, so String(number) can round to
and wrongly match a *different* bigint string. Replace the earlier
Number.isFinite check with Number.isSafeInteger, which also excludes
NaN/Infinity, so unreliable values decline to fast-match instead of
risking a false positive.

Tests:
- add an unsafe-integer case (9007199254740993 must not match the
  bigint string "9007199254740992") and confirm MAX_SAFE_INTEGER still
  matches its string form
- cover explicit null id-maps (the null-or-undefined test only exercised
  undefined)
- add a functional regression test (test/github-issues/11773) proving a
  bigint child's FK is not nulled when a parent is re-saved with a
  numeric in-memory child id (mysql/mariadb)
Address the Qodo review nit: the null id-map assertions cast through
`as any`. compareIds already handles null at runtime, so widen its
parameter types to `ObjectLiteral | undefined | null` and drop the casts.
…egers

Number.isSafeInteger also rejects finite decimals such as 1.5, so a
decimal primary key loaded as "1.5" no longer matched the in-memory 1.5
and persistence diffing could treat the row as removed. Only reject
integers beyond MAX_SAFE_INTEGER (which lose precision); finite
non-integers stringify faithfully and keep matching their string form.

Add a decimal-id test, and drop the redundant narrating comments from
the typeorm#11773 functional test.
String coercion only matched decimals whose string form was canonical, so
a scaled decimal key hydrated as "70.000" did not match the in-memory 70.
Compare the mixed string/number single-id fast path by numeric value
instead, so bigints returned as "1" and scaled decimals both match, while
still rejecting non-finite values and unsafe integers beyond
MAX_SAFE_INTEGER where a JS number cannot represent the id exactly.

Give the typeorm#11773 fixture an int parent PK and a bigint child PK so the
regression isolates the child orphan/FK-null path (a bigint parent could
otherwise fail parent matching first).
Number() accepts permissive forms ("" -> 0, "0x10" -> 16, "1e2" -> 100),
which could coerce a distinct string key into matching a number. Require
the string side of a mixed string/number id comparison to be a plain
decimal numeral before comparing numerically.
@Arul1998
Arul1998 force-pushed the fix/compare-ids-bigint-string branch from 3933180 to acd9d0f Compare September 18, 2026 15:54
@Arul1998

Copy link
Copy Markdown
Author

Thanks for the heads-up and the detailed migration notes, @michaelbromley no worries at all about the disruption.

I've rebased fix/compare-ids-bigint-string onto the new packages/typeorm layout using the recommended raised-rename-limit rebase. The two modified files replayed automatically; the new issue-11773 test files (which rename detection can't map since they're additions) I moved into packages/typeorm/test/github-issues/11773/ to match the new structure. Branch is pushed and the diff is now entirely under packages/typeorm/.

Verified locally: the package compiles cleanly and the OrmUtils unit suite passes (including the compareIds cases this PR adds). Ready for another look whenever you have a chance.

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

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

2 participants