Skip to content

fix: fix up map objects comparison - #10990

Merged
gioboa merged 2 commits into
typeorm:masterfrom
mgohin:fix/10989
Jan 15, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
mgohin:fix/10989

Conversation

@mgohin

@mgohin mgohin commented Jul 18, 2024 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #10989

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change (no need)
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • New Features

    • Deep comparison now supports Map and Set structures, enabling accurate structural equality checks for these types. This improves reliability in features that depend on deep comparisons across complex data.
  • Tests

    • Added unit tests validating deep comparison behavior for Map and Set, covering empty, identical, and size-mismatch scenarios.

@mgohin
mgohin force-pushed the fix/10989 branch 2 times, most recently from 9d0f161 to c7b5ba2 Compare July 18, 2024 16:18
@gioboa
gioboa requested review from alumni and sgarner September 18, 2025 08:00

@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 for the PR, can you solve the conflicts please?

@coderabbitai

coderabbitai Bot commented Sep 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds Map and Set normalization to the deep comparison in OrmUtils, converting Maps to objects and Sets to arrays before recursive checks. Updates internal comparisons to use normalized iterables. Extends unit tests to cover Map and Set scenarios for deepCompare.

Changes

Cohort / File(s) Summary
Deep compare Map/Set normalization
src/util/OrmUtils.ts
Normalize Map via Object.fromEntries and Set via Array.from; route all member/property checks and recursive calls through normalized iterableX/iterableY; maintain existing deep equality control flow with updated operands.
Unit tests for Map/Set
test/unit/util/orm-utils.ts
Add tests validating deepCompare behavior for Map and Set: equal empties, equal contents, and inequality when sizes differ.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant DC as OrmUtils.deepCompare
  participant N as Normalizer
  participant R as Recursive Check

  Caller->>DC: deepCompare(x, y)
  DC->>N: Determine types of x, y
  alt x is Map
    N-->>DC: iterableX = Object.fromEntries(x)\niterableY = Object.fromEntries(y)
    note over DC,N: Normalize Maps to plain objects
  else x is Set
    N-->>DC: iterableX = Array.from(x)\niterableY = Array.from(y)
    note over DC,N: Normalize Sets to arrays
  else
    N-->>DC: iterableX = x, iterableY = y
  end

  DC->>R: Compare keys/indices in iterableX vs iterableY
  loop for each property p
    R->>DC: recursive deepCompare(iterableX[p], iterableY[p])
    DC-->>R: boolean
  end
  DC-->>Caller: true/false
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

Poem

I sniffed through Maps, I hopped through Sets,
Aligned their shapes—no fuzzy bets.
Arrays from rings, objects from pairs,
I nibble edges, test who compares.
With every key and value met—
The burrow’s truth: equal or not yet. 🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix #10989 OrmUtils.deepCompare cannot compare Map objects" succinctly identifies the primary change and references the linked issue; it matches the changeset which implements Map comparison support in OrmUtils.deepCompare and adds related tests. The phrasing is concise and specific enough for a reviewer scanning PR history to understand the main purpose.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Sep 18, 2025 •

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

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

commit: 236f3bc

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/util/OrmUtils.ts (1)

470-495: Index using symbol-safe access once to reduce casts and fix TS typing.

Keep logic, but read props into locals to handle string|symbol keys.

-            switch (typeof iterableX[p]) {
+            const xProp = (iterableX as any)[p]
+            const yProp = (iterableY as any)[p]
+            switch (typeof xProp) {
                 case "object":
                 case "function":
                     leftChain.push(x)
                     rightChain.push(y)
                     if (
                         !OrmUtils.compare2Objects(
                             leftChain,
                             rightChain,
-                            iterableX[p],
-                            iterableY[p],
+                            xProp,
+                            yProp,
                         )
                     ) {
                         return false
                     }
                     leftChain.pop()
                     rightChain.pop()
                     break
                 default:
-                    if (iterableX[p] !== iterableY[p]) {
+                    if (xProp !== yProp) {
                         return false
                     }
                     break
             }
test/github-issues/10989/issue-10989.ts (1)

4-29: Add coverage for Map numeric/symbol/object keys and Set order-insensitivity.

Current tests miss the lossy cases; these would have caught the regressions.

     it("should compare two Map.", () => {
         expect(OrmUtils.deepCompare(new Map(), new Map())).to.equal(true)
         expect(
             OrmUtils.deepCompare(
                 new Map(Object.entries({ prop1: "value1", prop2: "value2" })),
                 new Map(Object.entries({ prop1: "value1", prop2: "value2" })),
             ),
         ).to.equal(true)
         expect(
             OrmUtils.deepCompare(
                 new Map(Object.entries({ prop1: "value1" })),
                 new Map(Object.entries({ prop1: "value1", prop2: "value2" })),
             ),
         ).to.equal(false)
+        // numeric vs string keys must differ
+        expect(OrmUtils.deepCompare(new Map([[1, "a"]]), new Map([["1", "a"]]))).to.equal(false)
+        // symbol keys must be compared
+        const s = Symbol("k")
+        expect(OrmUtils.deepCompare(new Map([[s, 1]]), new Map([[s, 1]]))).to.equal(true)
+        // object key by identity
+        const key = { a: 1 }
+        expect(OrmUtils.deepCompare(new Map([[key, 1]]), new Map([[key, 1]]))).to.equal(true)
     })
 
     it("should compare two Set.", () => {
         expect(OrmUtils.deepCompare(new Set(), new Set())).to.equal(true)
         expect(
             OrmUtils.deepCompare(new Set([1, 2, 3]), new Set([1, 2, 3])),
         ).to.equal(true)
         expect(
             OrmUtils.deepCompare(new Set([1, 2]), new Set([1, 2, 3])),
         ).to.equal(false)
+        // order-insensitive semantics
+        expect(
+            OrmUtils.deepCompare(new Set([3, 2, 1]), new Set([1, 2, 3])),
+        ).to.equal(true)
     })

Questions to confirm:

  • Should Maps with deep-equal but different object keys be considered equal, or must key identity match? Same for Sets of objects. Please confirm desired semantics.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 96ea431 and 203b4c6.

📒 Files selected for processing (2)
  • src/util/OrmUtils.ts (3 hunks)
  • test/github-issues/10989/issue-10989.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
test/github-issues/10989/issue-10989.ts (1)
src/util/OrmUtils.ts (1)
  • OrmUtils (8-599)

Comment thread src/util/OrmUtils.ts Resolved
Comment thread src/util/OrmUtils.ts Resolved
@mgohin

mgohin commented Sep 18, 2025

Copy link
Copy Markdown
Contributor Author

Conflicts resolved ;)

@coveralls

coveralls commented Sep 18, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.903% (+0.02%) from 80.888%
when pulling 236f3bc on mgohin:fix/10989
into 73227bc on typeorm:master.

@gioboa
gioboa requested a review from jovanadjuric September 18, 2025 08:57

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

Looks good thanks @mgohin , just needs a tweak to the tests.

Comment thread test/github-issues/10989/issue-10989.ts Resolved
@gioboa
gioboa requested a review from sgarner September 18, 2025 12:36
@mgohin
mgohin force-pushed the fix/10989 branch 3 times, most recently from af53333 to c5535f7 Compare September 18, 2025 13:14
@mgohin

mgohin commented Sep 18, 2025

Copy link
Copy Markdown
Contributor Author

The test parseSqlCheckExpression.parses a simple CHECK constraint was failing but did not directly touch it, I guess it is/was a formatting problem.
I guess it's ok now

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
test/unit/util/orm-utils.ts (2)

206-206: Name the suite after the public API being exercised.

You’re testing deepCompare, not the internal compare2Objects. Rename for clarity.

-    describe("compare2Objects", () => {
+    describe("deepCompare (Map/Set)", () => {

207-207: Tiny wording nit in test titles.

Pluralize for consistency.

-        it("should compare two Map.", () => {
+        it("should compare two Maps.", () => {
...
-        it("should compare two Set.", () => {
+        it("should compare two Sets.", () => {

Also applies to: 229-229

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 203b4c6 and b727efd.

📒 Files selected for processing (2)
  • src/util/OrmUtils.ts (3 hunks)
  • test/unit/util/orm-utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/util/OrmUtils.ts
🧰 Additional context used
🧬 Code graph analysis (1)
test/unit/util/orm-utils.ts (1)
src/util/OrmUtils.ts (1)
  • OrmUtils (8-599)
🔇 Additional comments (1)
test/unit/util/orm-utils.ts (1)

206-238: Solid new coverage for Map and Set equality paths.

These assertions exercise the happy paths and basic negatives for both Map and Set. Good placement and readable expectations.

Comment thread test/unit/util/orm-utils.test.ts Resolved
Comment thread test/unit/util/orm-utils.test.ts Resolved
Comment thread test/unit/util/orm-utils.test.ts Resolved
@mgohin

mgohin commented Oct 14, 2025

Copy link
Copy Markdown
Contributor Author

@sgarner is there anything else I have to do ?
I left a comment about the failing test #10990 (comment)

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

May I ask you to solve the conflicts please?

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

@mgohin thanks for opening this PR.
I'm closing this for now because it's stale, feel free to create a new PR with your improvements. 💪

@gioboa gioboa closed this Jan 15, 2026
@mgohin

mgohin commented Jan 15, 2026

Copy link
Copy Markdown
Contributor Author

Hi @gioboa,

I asked a question #10990 (comment) and never got an answer, it was to fix failing tests.

I'm sad to see my PR closed, I did put efforts in it

@gioboa

gioboa commented Jan 15, 2026

Copy link
Copy Markdown
Collaborator

Can you solve the conflicts please? We can review it without an aligned codebase.

@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

Set Order Dependency

Converting Set to Array for comparison may produce false negatives when Sets contain the same elements in different iteration orders. Sets are unordered collections, but Array.from preserves insertion order. Two Sets with identical elements but different insertion orders would be considered unequal.

} else if (x instanceof Set) {
    iterableX = Array.from(x)
    iterableY = Array.from(y)
Nested Map/Set Handling

The conversion of Map/Set to iterable objects happens only at the top level. If Maps or Sets are nested within the compared objects, they won't be properly converted during recursive comparison, potentially causing incorrect comparison results for deeply nested structures.

if (x instanceof Map) {
    iterableX = Object.fromEntries(x)
    iterableY = Object.fromEntries(y)
} else if (x instanceof Set) {
    iterableX = Array.from(x)
    iterableY = Array.from(y)
}

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

qodo-free-for-open-source-projects Bot commented Jan 15, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 236f3bc

CategorySuggestion                                                                                                                                    Impact
General
Add size check for performance

Add a size check for Map and Set comparisons to improve performance by failing
early if sizes differ.

src/util/OrmUtils.ts [464-470]

 if (x instanceof Map) {
+    if (x.size !== y.size) return false
     iterableX = Object.fromEntries(x)
     iterableY = Object.fromEntries(y)
 } else if (x instanceof Set) {
+    if (x.size !== y.size) return false
     iterableX = Array.from(x)
     iterableY = Array.from(y)
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: This is a valid performance optimization. Checking the size of Map and Set objects is a cheap way to fail early if they differ, avoiding more expensive conversions and comparisons.

Low
  • More

Previous suggestions

Suggestions up to commit 44b676a
CategorySuggestion                                                                                                                                    Impact
General
Add size comparison for early exit

Add a size comparison for Map and Set objects to allow for an early exit if they
differ, optimizing the comparison logic.

src/util/OrmUtils.ts [464-470]

 if (x instanceof Map) {
+    if (!(y instanceof Map) || x.size !== y.size) return false
     iterableX = Object.fromEntries(x)
     iterableY = Object.fromEntries(y)
 } else if (x instanceof Set) {
+    if (!(y instanceof Set) || x.size !== y.size) return false
     iterableX = Array.from(x)
     iterableY = Array.from(y)
 }
Suggestion importance[1-10]: 4

__

Why: This suggestion proposes a valid performance optimization by checking the size of Map or Set objects for an early exit, which is more efficient than the current implementation.

Low
Suggestions up to commit 657133d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate matching types before conversion

Add a type check to ensure y is an instance of Map or Set before conversion,
returning false if the types do not match to prevent runtime errors.

src/util/OrmUtils.ts [464-470]

 if (x instanceof Map) {
+    if (!(y instanceof Map)) return false
     iterableX = Object.fromEntries(x)
     iterableY = Object.fromEntries(y)
 } else if (x instanceof Set) {
+    if (!(y instanceof Set)) return false
     iterableX = Array.from(x)
     iterableY = Array.from(y)
 }
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a potential runtime error. If x is a Map or Set and y is not, calling Object.fromEntries(y) or Array.from(y) would cause a crash. Adding the type check prevents this bug.

Medium
General
Add size comparison for early exit

Add a size comparison for Map and Set objects to allow for an early false return
if their sizes differ, improving performance.

src/util/OrmUtils.ts [464-470]

 if (x instanceof Map) {
+    if (x.size !== y.size) return false
     iterableX = Object.fromEntries(x)
     iterableY = Object.fromEntries(y)
 } else if (x instanceof Set) {
+    if (x.size !== y.size) return false
     iterableX = Array.from(x)
     iterableY = Array.from(y)
 }
Suggestion importance[1-10]: 6

__

Why: This is a valid performance optimization. Checking the size of Map or Set objects allows for an early exit if they differ, avoiding unnecessary conversions and iterations. However, it should be applied after ensuring both objects are of the same type, as suggested in another review.

Low
Suggestions up to commit dc42540
CategorySuggestion                                                                                                                                    Impact
Security
Add security warning for Math.random fallback

Add a security warning when falling back to Math.random() for UUID generation,
as it is not cryptographically secure.

src/util/RandomGenerator.ts [9-31]

 static uuidv4(): string {
     // Try native crypto.randomUUID() (available in Node.js 19+ and modern browsers)
     const uuid = globalThis.crypto?.randomUUID?.()
     if (uuid) {
         return uuid
     }
     ...
     if (globalThis.crypto?.getRandomValues) {
         globalThis.crypto.getRandomValues(randomBytes)
     } else {
-        // Fallback for React Native/Hermes and environments without crypto support
-        ...
+        // Fallback for React Native/Hermes - NOT CRYPTOGRAPHICALLY SECURE
+        console.warn('Using Math.random() for UUID generation. This is NOT cryptographically secure and should not be used for security-sensitive operations.')
         for (let i = 0; i < 16; i++) {
             randomBytes[i] = Math.floor(Math.random() * 256)
         }
     }
Suggestion importance[1-10]: 8

__

Why: This is a valid and important security concern, as using Math.random() for UUIDs can lead to predictable identifiers, which is risky for security-sensitive applications.

Medium
Possible issue
Validate vector dimension calculation result

Ensure the calculated vector dimension is a positive integer before assigning
it.

src/driver/sqlserver/SqlServerQueryRunner.ts [3165-3173]

 if (tableColumn.type === "vector") {
     const len = +length
     // NOTE: real returned length is (N*4 + 8) where N is desired dimensions
     if (!Number.isNaN(len)) {
-        tableColumn.length = String(
-            (len - 8) / 4,
-        )
+        const dimensions = (len - 8) / 4
+        if (Number.isInteger(dimensions) && dimensions > 0) {
+            tableColumn.length = String(dimensions)
+        }
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that the vector dimension calculation could result in a non-integer, which is invalid. Adding a check for Number.isInteger improves the robustness and correctness of the logic.

Medium
Validate type consistency before conversion

Add type validation for the second argument y to ensure it matches the type of x
(Map or Set) before attempting conversion, preventing potential runtime errors.

src/util/OrmUtils.ts [464-470]

-if (x instanceof Map) {
+if (x instanceof Map && y instanceof Map) {
     iterableX = Object.fromEntries(x)
     iterableY = Object.fromEntries(y)
-} else if (x instanceof Set) {
+} else if (x instanceof Set && y instanceof Set) {
     iterableX = Array.from(x)
     iterableY = Array.from(y)
+} else if ((x instanceof Map || x instanceof Set) && !(y instanceof Map || y instanceof Set)) {
+    return false
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential runtime error if y is not of the same type as x (Map or Set). Adding a type check for y makes the comparison function more robust and prevents crashes on mismatched types.

Medium
Handle package version read errors

Add a try-catch block around the PlatformTools.readPackageVersion("redis") call
to handle potential errors if the redis package is not found.

src/cache/RedisQueryResultCache.ts [306-320]

 private detectRedisVersion(): void {
     if (this.clientType !== "redis") return
-    const version = PlatformTools.readPackageVersion("redis")
-    const major = parseInt(version.split(".")[0], 10)
-    if (isNaN(major)) {
-        throw new TypeORMError(`Invalid Redis version format: ${version}`)
-    }
-    if (major <= 4) {
-        // Redis 3/4 uses callback-based API
-        this.redisMajorVersion = 3
-    } else {
-        // Redis 5+ uses Promise-based API
-        this.redisMajorVersion = 5
+    try {
+        const version = PlatformTools.readPackageVersion("redis")
+        const major = parseInt(version.split(".")[0], 10)
+        if (isNaN(major)) {
+            throw new TypeORMError(`Invalid Redis version format: ${version}`)
+        }
+        if (major <= 4) {
+            // Redis 3/4 uses callback-based API
+            this.redisMajorVersion = 3
+        } else {
+            // Redis 5+ uses Promise-based API
+            this.redisMajorVersion = 5
+        }
+    } catch (error) {
+        throw new TypeORMError(`Failed to detect Redis version: ${error.message}`)
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies an unhandled exception from readPackageVersion if the redis package is missing, which would crash the application. Adding a try-catch block improves robustness and provides a more informative error message.

Medium
Check array length before comparison

Add a check to ensure the supportedIndexTypes array is not empty before calling
compareTableIndexTypes.

src/schema-builder/RdbmsSchemaBuilder.ts [393-401]

 if (
-    !!this.connection.driver.supportedIndexTypes &&
+    this.connection.driver.supportedIndexTypes &&
+    this.connection.driver.supportedIndexTypes.length > 0 &&
     typeof this.connection.driver.compareTableIndexTypes ===
         "function" &&
     !this.connection.driver.compareTableIndexTypes(
         indexMetadata,
         tableIndex,
     )
 )
     return true
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that an empty supportedIndexTypes array is truthy, which could lead to an incorrect call to compareTableIndexTypes, and proposes adding a length check to prevent this potential issue.

Low
General
Replace replaceAll with regex replace

Replace replaceAll with replace using a global regex to ensure compatibility
with older JavaScript environments.

src/driver/postgres/PostgresQueryRunner.ts [1605-1611]

-const escapedValue = item.replaceAll("'", "''")
+const escapedValue = item.replace(/'/g, "''")
 
 upQueries.push(
     new Query(
         `ALTER TYPE ${oldEnumName} ADD VALUE '${escapedValue}'`,
     ),
 )
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential compatibility issue with replaceAll in older Node.js versions and provides a valid, more compatible alternative.

Low
Suggestions up to commit b727efd
CategorySuggestion                                                                                                                                    Impact
Possible issue
Correctly compare Maps with non-string keys

Implement a correct Map comparison logic to handle non-string keys, as the
current Object.fromEntries approach leads to incorrect comparisons by
stringifying keys.

src/util/OrmUtils.ts [445-448]

-if (x instanceof Map) {
-    iterableX = Object.fromEntries(x)
-    iterableY = Object.fromEntries(y)
+if (x instanceof Map && y instanceof Map) {
+    if (x.size !== y.size) return false
+
+    for (const [key, value] of x) {
+        if (!y.has(key) || !OrmUtils.deepCompare(value, y.get(key))) {
+            return false
+        }
+    }
+    return true
 } else if (x instanceof Set) {
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical bug where Map comparison fails for non-string keys due to key stringification by Object.fromEntries, and it provides a robust, correct implementation.

High
Correctly compare Sets regardless of order

Implement a correct Set comparison logic that is independent of element order,
as the current array conversion approach is flawed.

src/util/OrmUtils.ts [448-451]

-} else if (x instanceof Set) {
-    iterableX = Array.from(x)
-    iterableY = Array.from(y)
+} else if (x instanceof Set && y instanceof Set) {
+    if (x.size !== y.size) return false
+
+    for (const xValue of x) {
+        let found = false
+        for (const yValue of y) {
+            if (OrmUtils.deepCompare(xValue, yValue)) {
+                found = true
+                break
+            }
+        }
+        if (!found) return false
+    }
+
+    return true
 }
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical bug where Set comparison is order-dependent due to array conversion, which is incorrect for sets. It provides a robust, order-independent comparison logic.

High

@mgohin mgohin reopened this Jan 15, 2026
@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

Set Order Dependency

Converting Set to Array for comparison may produce false negatives when Sets contain the same elements in different iteration orders. Sets are unordered collections, but Array.from() creates an ordered array. Two Sets with identical elements could fail comparison if their internal iteration orders differ.

} else if (x instanceof Set) {
    iterableX = Array.from(x)
    iterableY = Array.from(y)
Nested Map/Set Handling

When Maps or Sets contain nested Maps or Sets as values, the conversion to plain objects/arrays happens only at the top level. The recursive comparison may not properly handle these nested structures since they won't be converted before the recursive call.

if (x instanceof Map) {
    iterableX = Object.fromEntries(x)
    iterableY = Object.fromEntries(y)
} else if (x instanceof Set) {
    iterableX = Array.from(x)
    iterableY = Array.from(y)
}

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

Copy link
Copy Markdown

Persistent review updated to latest commit dc42540

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Implement correct Map and Set comparison

Refactor the Map and Set comparison logic to correctly handle non-string keys
and the unordered nature of sets, as the current implementation is flawed.

src/util/OrmUtils.ts [461-518]

-let iterableX = x
-let iterableY = y
+if (x instanceof Map) {
+    if (x.size !== y.size) return false
 
-if (x instanceof Map) {
-    iterableX = Object.fromEntries(x)
-    iterableY = Object.fromEntries(y)
-} else if (x instanceof Set) {
-    iterableX = Array.from(x)
-    iterableY = Array.from(y)
+    for (const [key, value] of x) {
+        // This is O(N^2), but is the only way to correctly compare maps with object keys.
+        const yValues = Array.from(y.entries())
+        const correspondingEntry = yValues.find((yEntry) =>
+            OrmUtils.deepCompare(key, yEntry[0]),
+        )
+        if (
+            correspondingEntry === undefined ||
+            !OrmUtils.deepCompare(value, correspondingEntry[1])
+        ) {
+            return false
+        }
+    }
+    return true
+}
+
+if (x instanceof Set) {
+    if (x.size !== y.size) return false
+
+    for (const xValue of x) {
+        // This is O(N^2), but is the only way to correctly compare sets with object values.
+        const yValues = Array.from(y.values())
+        const hasValue = yValues.some((yValue) =>
+            OrmUtils.deepCompare(xValue, yValue),
+        )
+        if (!hasValue) {
+            return false
+        }
+    }
+    return true
 }
 
 // Quick checking of one object being a subset of another.
 // todo: cache the structure of arguments[0] for performance
-for (p in iterableY) {
-    if (iterableY.hasOwnProperty(p) !== iterableX.hasOwnProperty(p)) {
+for (p in y) {
+    if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
         return false
-    } else if (typeof iterableY[p] !== typeof iterableX[p]) {
+    } else if (typeof y[p] !== typeof x[p]) {
         return false
     }
 }
 
-for (p in iterableX) {
-    if (iterableY.hasOwnProperty(p) !== iterableX.hasOwnProperty(p)) {
+for (p in x) {
+    if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
         return false
-    } else if (typeof iterableY[p] !== typeof iterableX[p]) {
+    } else if (typeof y[p] !== typeof x[p]) {
         return false
     }
 
-    switch (typeof iterableX[p]) {
+    switch (typeof x[p]) {
         case "object":
         case "function":
             leftChain.push(x)
             rightChain.push(y)
 
             if (
                 !OrmUtils.compare2Objects(
                     leftChain,
                     rightChain,
-                    iterableX[p],
-                    iterableY[p],
+                    x[p],
+                    y[p],
                 )
             ) {
                 return false
             }
 
             leftChain.pop()
             rightChain.pop()
             break
 
         default:
-            if (iterableX[p] !== iterableY[p]) {
+            if (x[p] !== y[p]) {
                 return false
             }
             break
     }
 }
 
 return true
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies that the PR's method for comparing Map and Set objects is flawed, as it doesn't handle non-string keys in Maps or the unordered nature of Sets, and provides a robust and correct implementation.

High
  • More

@mgohin mgohin changed the title fix #10989 OrmUtils.deepCompare cannot compare Map objects fix(utils) #10989 OrmUtils.deepCompare cannot compare Map objects Jan 15, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 657133d

1 similar comment
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 657133d

@mgohin mgohin changed the title fix(utils) #10989 OrmUtils.deepCompare cannot compare Map objects fix: #10989 OrmUtils.deepCompare cannot compare Map objects Jan 15, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 44b676a

@mgohin mgohin changed the title fix: #10989 OrmUtils.deepCompare cannot compare Map objects fix: OrmUtils.deepCompare cannot compare Map objects Jan 15, 2026
@mgohin mgohin changed the title fix: OrmUtils.deepCompare cannot compare Map objects fix: cannot compare Map objects in OrmUtils.deepCompare Jan 15, 2026
@mgohin

mgohin commented Jan 15, 2026

Copy link
Copy Markdown
Contributor Author

@gioboa it's done, I got stuck 15 min with the PR title semantic ... a real pain ><

@gioboa

gioboa commented Jan 15, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the feedback, I'm struggling with it too 😅

@gioboa
gioboa requested review from G0maa, naorpeled and sgarner and removed request for jovanadjuric and sgarner January 15, 2026 10:12

@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 👏
Thanks for your commitment and help @mgohin

@gioboa
gioboa dismissed sgarner’s stale review January 15, 2026 10:24

The author addressed the comment.

@gioboa gioboa changed the title fix: cannot compare Map objects in OrmUtils.deepCompare fix: fix up map objects comparison Jan 15, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 236f3bc

@gioboa
gioboa merged commit f66eee7 into typeorm:master Jan 15, 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.

OrmUtils.deepCompare cannot compare Map objects

6 participants