Skip to content

fix: scope invalidWhereValuesBehavior to high-level abstractions only - #11878

Merged
naorpeled merged 7 commits into
masterfrom
fix/invalid-where-values-behavior-nested-relations
Mar 8, 2026
Merged

naorpeled merged 7 commits into
masterfrom
fix/invalid-where-values-behavior-nested-relations

Conversation

@naorpeled

@naorpeled naorpeled commented Dec 27, 2025 •

Copy link
Copy Markdown
Member

Problem

invalidWhereValuesBehavior was being applied to QueryBuilder's .where() method, which is a low-level API. This meant that users who set null: "throw" or undefined: "throw" would get errors even when using QB directly — where they might intentionally be passing dynamic values and handling the SQL themselves.

The setting should only guard against accidental null/undefined in high-level APIs like .find(), repository.update(), and manager.delete(), where null/undefined silently changes query semantics (e.g., findBy({ id: undefined }) returns the first row).

Changes

Core

  • Removed invalidWhereValuesBehavior checks from QueryBuilder.getWherePredicateCondition() — QB .where() now passes null/undefined through as-is (pre-feature behavior)
  • Added OrmUtils.validateWhereCriteria() — recursive validation for object-style where criteria, called before QB execution
  • Added validation calls in EntityManager.update(), .delete(), .softDelete(), .restore() (object criteria branch)
  • Enhanced nested relation handling in SelectQueryBuilder.buildWhere() — throws on all-undefined nested objects when configured

Tests

  • find-options.test.ts — converted QB .where() calls to .setFindOptions(), added nested relation partial-undefined test
  • query-builders.test.ts — rewritten to test EntityManager/Repository methods, added tests verifying QB .where() is unaffected

Docs

  • Updated null/undefined handling docs to reflect the scoped behavior
  • Added section documenting how null/undefined actually behave in QB .where() (generates WHERE col = NULL, always false)
  • Added summary table comparing behavior across high-level vs low-level APIs

What's affected

API invalidWhereValuesBehavior applies?
repository.find() / findOne() / findBy() Yes
manager.update() / delete() / softDelete() / restore() Yes
repository.update() / delete() Yes
qb.setFindOptions() Yes
qb.where() / .andWhere() / .orWhere() No

Copilot AI review requested due to automatic review settings December 27, 2025 20:57
@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: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Logic Consistency

The nested relation validation logic checks if all keys are undefined and throws an error when undefinedBehavior === 'throw'. However, this only validates the first level of nesting. If where[key] contains deeply nested objects with undefined values, they may not be validated. Consider whether recursive validation is needed for consistency.

const undefinedKeys = Object.keys(where[key]).filter(
    (k) => where[key][k] === undefined,
)
const allAllUndefined =
    undefinedKeys.length ===
    Object.keys(where[key]).length
if (allAllUndefined) {
    const undefinedBehavior =
        this.connection.options
            .invalidWhereValuesBehavior?.undefined ||
        "ignore"
    if (undefinedBehavior === "throw") {
        // Report nested path for first undefined key
        const firstUndefinedKey = undefinedKeys[0]
        throw new TypeORMError(
            `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
                `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
        )
    }
    continue
Validation Timing

The validateWhereParameters method is called before setParameters in all query builder methods. However, if parameters contain complex objects or nested structures (not just primitives), the validation may not catch all cases. Verify that the validation covers all parameter types that could be passed to where clauses.

protected validateWhereParameters(parameters?: ObjectLiteral): void {
    if (!parameters) return

    const nullBehavior =
        this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
    const undefinedBehavior =
        this.connection.options.invalidWhereValuesBehavior?.undefined ||
        "ignore"

    for (const [key, value] of Object.entries(parameters)) {
        if (value === null && nullBehavior === "throw") {
            throw new TypeORMError(
                `Null value encountered in parameter ':${key}' of a where condition. ` +
                    `To match with SQL NULL, the IsNull() operator must be used. ` +
                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
            )
        }
        if (value === undefined && undefinedBehavior === "throw") {
            throw new TypeORMError(
                `Undefined value encountered in parameter ':${key}' of a where condition. ` +
                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
            )
        }
    }
}

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

qodo-free-for-open-source-projects Bot commented Dec 27, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to e2a7a47

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate nested parameter values

Implement deep validation for parameters in validateWhereParameters to detect
null or undefined values within nested objects and arrays, which the current
shallow check misses.

src/query-builder/QueryBuilder.ts [418-442]

 protected validateWhereParameters(parameters?: ObjectLiteral): void {
     if (!parameters) return
 
     const nullBehavior =
         this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
     const undefinedBehavior =
         this.connection.options.invalidWhereValuesBehavior?.undefined ||
         "ignore"
 
-    for (const [key, value] of Object.entries(parameters)) {
+    const visit = (value: any, path: string) => {
         if (value === null && nullBehavior === "throw") {
             throw new TypeORMError(
-                `Null value encountered in parameter ':${key}' of a where condition. ` +
+                `Null value encountered in parameter ':${path}' of a where condition. ` +
                     `To match with SQL NULL, the IsNull() operator must be used. ` +
                     `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
             )
         }
+
         if (value === undefined && undefinedBehavior === "throw") {
             throw new TypeORMError(
-                `Undefined value encountered in parameter ':${key}' of a where condition. ` +
+                `Undefined value encountered in parameter ':${path}' of a where condition. ` +
                     `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
             )
         }
+
+        if (Array.isArray(value)) {
+            for (let i = 0; i < value.length; i++) {
+                visit(value[i], `${path}[${i}]`)
+            }
+            return
+        }
+
+        if (value && typeof value === "object") {
+            for (const [k, v] of Object.entries(value)) {
+                visit(v, `${path}.${k}`)
+            }
+        }
+    }
+
+    for (const [key, value] of Object.entries(parameters)) {
+        visit(value, key)
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the new validateWhereParameters method only performs a shallow check, and proposes a recursive validation to handle nested null or undefined values, which would improve the robustness of the feature.

Medium
  • Update

Previous suggestions

✅ Suggestions up to commit 29ca732
CategorySuggestion                                                                                                                                    Impact
Possible issue
Recursively validate parameter objects

Implement recursive validation in validateWhereParameters to check for null or
undefined values within nested parameter objects, ensuring consistent behavior
with other parts of the query builder.

src/query-builder/QueryBuilder.ts [418-442]

 protected validateWhereParameters(parameters?: ObjectLiteral): void {
     if (!parameters) return
 
     const nullBehavior =
         this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
     const undefinedBehavior =
         this.connection.options.invalidWhereValuesBehavior?.undefined ||
         "ignore"
 
-    for (const [key, value] of Object.entries(parameters)) {
+    const visit = (value: any, path: string) => {
         if (value === null && nullBehavior === "throw") {
             throw new TypeORMError(
-                `Null value encountered in parameter ':${key}' of a where condition. ` +
+                `Null value encountered in parameter ':${path}' of a where condition. ` +
                     `To match with SQL NULL, the IsNull() operator must be used. ` +
                     `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
             )
         }
         if (value === undefined && undefinedBehavior === "throw") {
             throw new TypeORMError(
-                `Undefined value encountered in parameter ':${key}' of a where condition. ` +
+                `Undefined value encountered in parameter ':${path}' of a where condition. ` +
                     `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
             )
         }
+
+        if (
+            value &&
+            typeof value === "object" &&
+            !Array.isArray(value) &&
+            !InstanceChecker.isFindOperator(value)
+        ) {
+            for (const [k, v] of Object.entries(value)) {
+                visit(v, `${path}.${k}`)
+            }
+        }
+    }
+
+    for (const [key, value] of Object.entries(parameters)) {
+        visit(value, key)
     }
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly points out that the new validation for null/undefined parameters is not recursive, which is inconsistent with how nested objects are handled elsewhere in the PR and can lead to missed validation in common use cases.

Medium
Fix empty-object undefined detection

To prevent incorrect behavior with empty relation objects, modify the logic to
ensure that the check for all-undefined properties only applies to non-empty
objects.

src/query-builder/QueryBuilder.ts [1417-1439]

 // Check if all properties of the nested relation object are undefined
 // This handles the case when user defines conditional queries with undefined values
-if (typeof entity[key] === "object") {
-    const undefinedKeys = Object.keys(entity[key]).filter(
-        (k) => entity[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length === Object.keys(entity[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options.invalidWhereValuesBehavior
-                ?.undefined || "ignore"
-        if (undefinedBehavior === "throw") {
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+if (
+    entity[key] &&
+    typeof entity[key] === "object" &&
+    !Array.isArray(entity[key]) &&
+    !InstanceChecker.isFindOperator(entity[key])
+) {
+    const relationKeys = Object.keys(entity[key])
+    if (relationKeys.length > 0) {
+        const undefinedKeys = relationKeys.filter(
+            (k) => entity[key][k] === undefined,
+        )
+        const allAllUndefined = undefinedKeys.length === relationKeys.length
+
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options.invalidWhereValuesBehavior
+                    ?.undefined || "ignore"
+            if (undefinedBehavior === "throw") {
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            // Skip this relation if behavior is 'ignore'
+            continue
         }
-        // Skip this relation if behavior is 'ignore'
-        continue
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty object in a relation query would be incorrectly treated as having all-undefined properties, leading to a confusing error or incorrect query behavior.

Medium
Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard against empty nested objects

In createPropertyPath, add a check to ensure a nested relation object is not
empty before validating its properties for undefined values. This prevents
incorrect error messages for empty objects.

src/query-builder/QueryBuilder.ts [1419-1439]

 if (typeof entity[key] === "object") {
-    const undefinedKeys = Object.keys(entity[key]).filter(
-        (k) => entity[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length === Object.keys(entity[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options.invalidWhereValuesBehavior
-                ?.undefined || "ignore"
-        if (undefinedBehavior === "throw") {
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(entity[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => entity[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options.invalidWhereValuesBehavior
+                    ?.undefined || "ignore"
+            if (undefinedBehavior === "throw") {
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            // Skip this relation if behavior is 'ignore'
+            continue
         }
-        // Skip this relation if behavior is 'ignore'
-        continue
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
✅ Avoid empty-object undefined detection
Suggestion Impact:The commit updated the nested-object undefined detection to require the nested where object to have at least one key (whereKeys.length > 0) before considering it "all undefined", preventing empty objects from being misclassified; it also added undefined-behavior handling for this case.

code diff:

                     // if all properties of where are undefined we don't need to join anything
                     // this can happen when user defines map with conditional queries inside
                     if (typeof where[key] === "object") {
-                        const allAllUndefined = Object.keys(where[key]).every(
-                            (k) => where[key][k] === undefined,
-                        )
+                        const whereKeys = Object.keys(where[key])
+                        const allAllUndefined =
+                            whereKeys.length > 0 &&
+                            whereKeys.every((k) => where[key][k] === undefined)
                         if (allAllUndefined) {
+                            const undefinedBehavior =
+                                this.connection.options
+                                    .invalidWhereValuesBehavior?.undefined ||
+                                "ignore"
+                            if (undefinedBehavior === "throw") {
+                                throw new TypeORMError(
+                                    `Undefined value encountered in nested relation '${alias}.${key}' of a where condition. ` +
+                                        `All properties of the nested object are undefined. ` +
+                                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                                )
+                            }
                             continue
                         }
                     }

In buildWhere, add a check to ensure a nested where object is not empty before
validating its properties for undefined values. This prevents incorrect error
messages for empty objects.

src/query-builder/SelectQueryBuilder.ts [4534-4556]

 if (typeof where[key] === "object") {
-    const undefinedKeys = Object.keys(where[key]).filter(
-        (k) => where[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length ===
-        Object.keys(where[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options
-                .invalidWhereValuesBehavior?.undefined ||
-            "ignore"
-        if (undefinedBehavior === "throw") {
-            // Report nested path for first undefined key
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(where[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => where[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options
+                    .invalidWhereValuesBehavior?.undefined ||
+                "ignore"
+            if (undefinedBehavior === "throw") {
+                // Report nested path for first undefined key
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            continue
         }
-        continue
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
General
✅ Fix misleading null error text
Suggestion Impact:The commit removed the QueryBuilder null/undefined where-condition validation block (including the misleading error text that referenced 'sql-null'), instead of updating the message in validateWhereParameters.

code diff:

@@ -1581,32 +1608,6 @@
                     parameters: [aliasPath, ...parameters],
                 }
             }
-        } else if (parameterValue === null) {
-            const nullBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.null ||
-                "ignore"
-            if (nullBehavior === "sql-null") {
-                return {
-                    operator: "isNull",
-                    parameters: [aliasPath],
-                }
-            } else if (nullBehavior === "throw") {
-                throw new TypeORMError(
-                    `Null value encountered in property '${aliasPath}' of a where condition. ` +
-                        `To match with SQL NULL, the IsNull() operator must be used. ` +
-                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
-                )
-            }
-        } else if (parameterValue === undefined) {
-            const undefinedBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.undefined ||
-                "ignore"
-            if (undefinedBehavior === "throw") {
-                throw new TypeORMError(
-                    `Undefined value encountered in property '${aliasPath}' of a where condition. ` +
-                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-                )
-            }
         }

In validateWhereParameters, update the error message for null values to remove
the misleading suggestion of using the 'sql-null' option, as it cannot be
automatically applied to string-based queries.

src/query-builder/QueryBuilder.ts [418-442]

 protected validateWhereParameters(parameters?: ObjectLiteral): void {
     if (!parameters) return
 
     const nullBehavior =
         this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
     const undefinedBehavior =
         this.connection.options.invalidWhereValuesBehavior?.undefined ||
         "ignore"
 
     for (const [key, value] of Object.entries(parameters)) {
         if (value === null && nullBehavior === "throw") {
             throw new TypeORMError(
                 `Null value encountered in parameter ':${key}' of a where condition. ` +
-                    `To match with SQL NULL, the IsNull() operator must be used. ` +
-                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                    `To match SQL NULL in QueryBuilder string conditions, use the IsNull() operator in object-literal where clauses, or rewrite the condition to use IS NULL. ` +
+                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' in connection options to skip this validation.`,
             )
         }
         if (value === undefined && undefinedBehavior === "throw") {
             throw new TypeORMError(
                 `Undefined value encountered in parameter ':${key}' of a where condition. ` +
                     `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
             )
         }
     }
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that the error message for null parameters is misleading, as the 'sql-null' option is not applicable in this context, and proposes a clearer message.

Low

@pkg-pr-new

pkg-pr-new Bot commented Dec 27, 2025 •

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

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

commit: dc1064c

@naorpeled
naorpeled changed the base branch from master to v0.3 December 27, 2025 20:59
@naorpeled
naorpeled marked this pull request as draft December 27, 2025 20:59

Copilot AI 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.

Pull request overview

This PR fixes a bug where the invalidWhereValuesBehavior configuration with undefined: 'throw' was not properly throwing errors in two specific scenarios: (1) nested relation objects with other valid predicates in find options, and (2) string-based where parameters in QueryBuilder methods.

Key changes:

  • Added validation logic to throw errors when all nested relation properties are undefined
  • Implemented validateWhereParameters helper method to validate null/undefined values in QueryBuilder string parameters
  • Applied parameter validation across all QueryBuilder where/andWhere/orWhere methods

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/query-builder/QueryBuilder.ts Adds validateWhereParameters helper method to validate null/undefined values in where parameters
src/query-builder/SelectQueryBuilder.ts Adds validation calls in where methods and fixes nested relation undefined value handling in buildWhere
src/query-builder/UpdateQueryBuilder.ts Adds validation calls before setParameters in where/andWhere/orWhere methods
src/query-builder/DeleteQueryBuilder.ts Adds validation calls before setParameters in where/andWhere/orWhere methods
src/query-builder/SoftDeleteQueryBuilder.ts Adds validation calls before setParameters in where/andWhere/orWhere methods
test/functional/null-undefined-handling/find-options.test.ts Adds regression test for nested relation objects with other valid predicates
test/functional/null-undefined-handling/query-builders.test.ts Adds regression tests for undefined and null values in string where parameters
docs/docusaurus.config.ts Adds version dropdown to documentation navbar (unrelated to bug fix)
docs/docs/query-runner.md Adds link to QueryRunner API documentation (unrelated to bug fix)

Comment thread docs/docs/query-runner.md Resolved
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Dec 27, 2025 •

Copy link
Copy Markdown

Deploying typeorm with  Cloudflare Pages  Cloudflare Pages

Latest commit: dc1064c
Status: ✅  Deploy successful!
Preview URL: https://33e87056.typeorm.pages.dev
Branch Preview URL: https://fix-invalid-where-values-beh.typeorm.pages.dev

View logs

@naorpeled
naorpeled marked this pull request as ready for review December 28, 2025 18:05
@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: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Validation Timing

The validateWhereParameters method is called before setParameters, but it only validates the top-level parameters object. If parameters contain nested objects or arrays, those nested values won't be validated. Consider whether nested parameter validation is needed for completeness.

protected validateWhereParameters(parameters?: ObjectLiteral): void {
    if (!parameters) return

    const nullBehavior =
        this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
    const undefinedBehavior =
        this.connection.options.invalidWhereValuesBehavior?.undefined ||
        "ignore"

    for (const [key, value] of Object.entries(parameters)) {
        if (value === null && nullBehavior === "throw") {
            throw new TypeORMError(
                `Null value encountered in parameter ':${key}' of a where condition. ` +
                    `To match with SQL NULL, the IsNull() operator must be used. ` +
                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
            )
        }
        if (value === undefined && undefinedBehavior === "throw") {
            throw new TypeORMError(
                `Undefined value encountered in parameter ':${key}' of a where condition. ` +
                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
            )
        }
    }
}
Code Duplication

The logic for checking if all relation properties are undefined and throwing errors is duplicated in two places (lines 1419-1439 and 4535-4560). This duplication increases maintenance burden and risk of inconsistency. Consider extracting this into a shared helper method.

    const undefinedKeys = Object.keys(where[key]).filter(
        (k) => where[key][k] === undefined,
    )
    const allAllUndefined =
        undefinedKeys.length ===
        Object.keys(where[key]).length
    if (allAllUndefined) {
        const undefinedBehavior =
            this.connection.options
                .invalidWhereValuesBehavior?.undefined ||
            "ignore"
        if (undefinedBehavior === "throw") {
            // Report nested path for first undefined key
            const firstUndefinedKey = undefinedKeys[0]
            throw new TypeORMError(
                `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
            )
        }
        continue
    }
}

if (InstanceChecker.isFindOperator(where[key])) {
    if (
        where[key].type === "moreThan" ||
Variable Naming

The variable name allAllUndefined appears to be a typo (double 'all'). Should likely be allUndefined for clarity and consistency.

const allAllUndefined =
    undefinedKeys.length ===
    Object.keys(where[key]).length
if (allAllUndefined) {

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

qodo-free-for-open-source-projects Bot commented Dec 28, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard against empty nested objects

In createPropertyPath, add a check to ensure a nested relation object is not
empty before validating its properties for undefined values. This prevents
incorrect error messages for empty objects.

src/query-builder/QueryBuilder.ts [1419-1439]

 if (typeof entity[key] === "object") {
-    const undefinedKeys = Object.keys(entity[key]).filter(
-        (k) => entity[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length === Object.keys(entity[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options.invalidWhereValuesBehavior
-                ?.undefined || "ignore"
-        if (undefinedBehavior === "throw") {
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(entity[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => entity[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options.invalidWhereValuesBehavior
+                    ?.undefined || "ignore"
+            if (undefinedBehavior === "throw") {
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            // Skip this relation if behavior is 'ignore'
+            continue
         }
-        // Skip this relation if behavior is 'ignore'
-        continue
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
✅ Avoid empty-object undefined detection
Suggestion Impact:The commit introduced a cached key list (whereKeys) and updated the allAllUndefined condition to require whereKeys.length > 0, preventing empty nested objects from being treated as all-undefined.

code diff:

                     if (typeof where[key] === "object") {
-                        const undefinedKeys = Object.keys(where[key]).filter(
+                        const whereKeys = Object.keys(where[key])
+                        const undefinedKeys = whereKeys.filter(
                             (k) => where[key][k] === undefined,
                         )
                         const allAllUndefined =
-                            undefinedKeys.length ===
-                            Object.keys(where[key]).length
+                            whereKeys.length > 0 &&
+                            undefinedKeys.length === whereKeys.length
                         if (allAllUndefined) {

In buildWhere, add a check to ensure a nested where object is not empty before
validating its properties for undefined values. This prevents incorrect error
messages for empty objects.

src/query-builder/SelectQueryBuilder.ts [4534-4556]

 if (typeof where[key] === "object") {
-    const undefinedKeys = Object.keys(where[key]).filter(
-        (k) => where[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length ===
-        Object.keys(where[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options
-                .invalidWhereValuesBehavior?.undefined ||
-            "ignore"
-        if (undefinedBehavior === "throw") {
-            // Report nested path for first undefined key
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(where[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => where[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options
+                    .invalidWhereValuesBehavior?.undefined ||
+                "ignore"
+            if (undefinedBehavior === "throw") {
+                // Report nested path for first undefined key
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            continue
         }
-        continue
     }
 }

[Suggestion processed]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
General
✅ Fix misleading null error text
Suggestion Impact:Instead of updating the error message, the commit removed the null/undefined handling branch that threw the misleading "sql-null" error message for where-condition properties (including the 'sql-null' wording), effectively eliminating that misleading guidance from this code path.

code diff:

-        } else if (parameterValue === null) {
-            const nullBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.null ||
-                "ignore"
-            if (nullBehavior === "sql-null") {
-                return {
-                    operator: "isNull",
-                    parameters: [aliasPath],
-                }
-            } else if (nullBehavior === "throw") {
-                throw new TypeORMError(
-                    `Null value encountered in property '${aliasPath}' of a where condition. ` +
-                        `To match with SQL NULL, the IsNull() operator must be used. ` +
-                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
-                )
-            }
-        } else if (parameterValue === undefined) {
-            const undefinedBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.undefined ||
-                "ignore"
-            if (undefinedBehavior === "throw") {
-                throw new TypeORMError(
-                    `Undefined value encountered in property '${aliasPath}' of a where condition. ` +
-                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-                )
-            }
         }

In validateWhereParameters, update the error message for null values to remove
the misleading suggestion of using the 'sql-null' option, as it cannot be
automatically applied to string-based queries.

src/query-builder/QueryBuilder.ts [418-442]

 protected validateWhereParameters(parameters?: ObjectLiteral): void {
     if (!parameters) return
 
     const nullBehavior =
         this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
     const undefinedBehavior =
         this.connection.options.invalidWhereValuesBehavior?.undefined ||
         "ignore"
 
     for (const [key, value] of Object.entries(parameters)) {
         if (value === null && nullBehavior === "throw") {
             throw new TypeORMError(
                 `Null value encountered in parameter ':${key}' of a where condition. ` +
-                    `To match with SQL NULL, the IsNull() operator must be used. ` +
-                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                    `To match SQL NULL in QueryBuilder string conditions, use the IsNull() operator in object-literal where clauses, or rewrite the condition to use IS NULL. ` +
+                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' in connection options to skip this validation.`,
             )
         }
         if (value === undefined && undefinedBehavior === "throw") {
             throw new TypeORMError(
                 `Undefined value encountered in parameter ':${key}' of a where condition. ` +
                     `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
             )
         }
     }
 }

[Suggestion processed]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that the error message for null parameters is misleading, as the 'sql-null' option is not applicable in this context, and proposes a clearer message.

Low
  • More

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

It looks a good piece of code to me 👏 @naorpeled

@alumni

alumni commented Jan 2, 2026

Copy link
Copy Markdown
Collaborator

Seems that we call validateWhereParameters every time before setParameters. I got a bit confused by this and was wondering why can we validate the parameters when we set them :P But then I realized we're validating the FindOptionsWhere argument. Maybe we can name the function to imply that this is what we validate ;)

@naorpeled

Copy link
Copy Markdown
Member Author

Seems that we call validateWhereParameters every time before setParameters. I got a bit confused by this and was wondering why can we validate the parameters when we set them :P But then I realized we're validating the FindOptionsWhere argument. Maybe we can name the function to imply that this is what we validate ;)

Good point, wdyt about enforceInvalidWhereValuesBehavior?

@naorpeled
naorpeled requested a review from sgarner January 19, 2026 22:39
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Feb 13, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Guard against empty nested objects

In createPropertyPath, add a check to ensure a nested relation object is not
empty before validating its properties for undefined values. This prevents
incorrect error messages for empty objects.

src/query-builder/QueryBuilder.ts [1419-1439]

 if (typeof entity[key] === "object") {
-    const undefinedKeys = Object.keys(entity[key]).filter(
-        (k) => entity[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length === Object.keys(entity[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options.invalidWhereValuesBehavior
-                ?.undefined || "ignore"
-        if (undefinedBehavior === "throw") {
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(entity[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => entity[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options.invalidWhereValuesBehavior
+                    ?.undefined || "ignore"
+            if (undefinedBehavior === "throw") {
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            // Skip this relation if behavior is 'ignore'
+            continue
         }
-        // Skip this relation if behavior is 'ignore'
-        continue
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
✅ Avoid empty-object undefined detection
Suggestion Impact:The commit stores nested object keys in a variable and updates the allAllUndefined condition to require whereKeys.length > 0, preventing empty nested objects from being treated as all-undefined.

code diff:

                     if (typeof where[key] === "object") {
-                        const undefinedKeys = Object.keys(where[key]).filter(
+                        const whereKeys = Object.keys(where[key])
+                        const undefinedKeys = whereKeys.filter(
                             (k) => where[key][k] === undefined,
                         )
                         const allAllUndefined =
-                            undefinedKeys.length ===
-                            Object.keys(where[key]).length
+                            whereKeys.length > 0 &&
+                            undefinedKeys.length === whereKeys.length
                         if (allAllUndefined) {

In buildWhere, add a check to ensure a nested where object is not empty before
validating its properties for undefined values. This prevents incorrect error
messages for empty objects.

src/query-builder/SelectQueryBuilder.ts [4534-4556]

 if (typeof where[key] === "object") {
-    const undefinedKeys = Object.keys(where[key]).filter(
-        (k) => where[key][k] === undefined,
-    )
-    const allAllUndefined =
-        undefinedKeys.length ===
-        Object.keys(where[key]).length
-    if (allAllUndefined) {
-        const undefinedBehavior =
-            this.connection.options
-                .invalidWhereValuesBehavior?.undefined ||
-            "ignore"
-        if (undefinedBehavior === "throw") {
-            // Report nested path for first undefined key
-            const firstUndefinedKey = undefinedKeys[0]
-            throw new TypeORMError(
-                `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
-                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-            )
+    const keys = Object.keys(where[key])
+    if (keys.length > 0) {
+        const undefinedKeys = keys.filter((k) => where[key][k] === undefined)
+        const allAllUndefined = undefinedKeys.length === keys.length
+        if (allAllUndefined) {
+            const undefinedBehavior =
+                this.connection.options
+                    .invalidWhereValuesBehavior?.undefined ||
+                "ignore"
+            if (undefinedBehavior === "throw") {
+                // Report nested path for first undefined key
+                const firstUndefinedKey = undefinedKeys[0]
+                throw new TypeORMError(
+                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+            continue
         }
-        continue
     }
 }

[Suggestion processed]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a bug in the new logic where an empty nested object is mishandled, leading to confusing error messages or incorrect behavior, and provides a correct fix.

Medium
General
✅ Fix misleading null error text
Suggestion Impact:The commit removed the null/undefined handling branch that threw an error mentioning the 'sql-null' option (and also removed the 'sql-null' auto-handling path) in the where-condition building logic, eliminating the misleading 'sql-null' guidance rather than rewriting the error text in validateWhereParameters.

code diff:

@@ -1572,32 +1608,6 @@
                     parameters: [aliasPath, ...parameters],
                 }
             }
-        } else if (parameterValue === null) {
-            const nullBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.null ||
-                "ignore"
-            if (nullBehavior === "sql-null") {
-                return {
-                    operator: "isNull",
-                    parameters: [aliasPath],
-                }
-            } else if (nullBehavior === "throw") {
-                throw new TypeORMError(
-                    `Null value encountered in property '${aliasPath}' of a where condition. ` +
-                        `To match with SQL NULL, the IsNull() operator must be used. ` +
-                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
-                )
-            }
-        } else if (parameterValue === undefined) {
-            const undefinedBehavior =
-                this.connection.options.invalidWhereValuesBehavior?.undefined ||
-                "ignore"
-            if (undefinedBehavior === "throw") {
-                throw new TypeORMError(
-                    `Undefined value encountered in property '${aliasPath}' of a where condition. ` +
-                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
-                )
-            }
         }

In validateWhereParameters, update the error message for null values to remove
the misleading suggestion of using the 'sql-null' option, as it cannot be
automatically applied to string-based queries.

src/query-builder/QueryBuilder.ts [418-442]

 protected validateWhereParameters(parameters?: ObjectLiteral): void {
     if (!parameters) return
 
     const nullBehavior =
         this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
     const undefinedBehavior =
         this.connection.options.invalidWhereValuesBehavior?.undefined ||
         "ignore"
 
     for (const [key, value] of Object.entries(parameters)) {
         if (value === null && nullBehavior === "throw") {
             throw new TypeORMError(
                 `Null value encountered in parameter ':${key}' of a where condition. ` +
-                    `To match with SQL NULL, the IsNull() operator must be used. ` +
-                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                    `To match SQL NULL in QueryBuilder string conditions, use the IsNull() operator in object-literal where clauses, or rewrite the condition to use IS NULL. ` +
+                    `Set 'invalidWhereValuesBehavior.null' to 'ignore' in connection options to skip this validation.`,
             )
         }
         if (value === undefined && undefinedBehavior === "throw") {
             throw new TypeORMError(
                 `Undefined value encountered in parameter ':${key}' of a where condition. ` +
                     `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
             )
         }
     }
 }

[Suggestion processed]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that the error message for null parameters is misleading, as the 'sql-null' option is not applicable in this context, and proposes a clearer message.

Low
  • More

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

qodo-free-for-open-source-projects Bot commented Feb 13, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (62) 📘 Rule violations (13) 📎 Requirement gaps (0)

Grey Divider


Action required

1. __proto__ key pollution 🐞 Bug ⛨ Security ⭐ New
Description
normalizeWhereCriteria copies user-provided keys into a plain object without filtering dangerous
keys like __proto__, enabling prototype pollution if criteria comes from untrusted input. This is
inconsistent with existing OrmUtils.merge(), which explicitly blocks __proto__.
Code

src/util/OrmUtils.ts[R660-703]

+        const result: ObjectLiteral = {}
+
+        for (const [key, value] of Object.entries(criteria)) {
+            const propertyPath = path ? `${path}.${key}` : key
+
+            if (value === undefined) {
+                const behavior = options.undefined || "ignore"
+                if (behavior === "throw") {
+                    throw new TypeORMError(
+                        `Undefined value encountered in property '${propertyPath}' of a where condition. ` +
+                            `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                    )
+                }
+                // "ignore" — skip this key
+            } else if (value === null) {
+                const behavior = options.null || "ignore"
+                if (behavior === "throw") {
+                    throw new TypeORMError(
+                        `Null value encountered in property '${propertyPath}' of a where condition. ` +
+                            `To match with SQL NULL, the IsNull() operator must be used. ` +
+                            `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                    )
+                } else if (behavior === "sql-null") {
+                    result[key] = IsNull()
+                }
+                // "ignore" — skip this key
+            } else if (
+                typeof value === "object" &&
+                !Array.isArray(value) &&
+                !(value instanceof Date) &&
+                !InstanceChecker.isFindOperator(value)
+            ) {
+                const nested = OrmUtils.normalizeWhereCriteria(
+                    value,
+                    options,
+                    propertyPath,
+                )
+                if (Object.keys(nested).length > 0) {
+                    result[key] = nested
+                }
+            } else {
+                result[key] = value
+            }
+        }
Evidence
normalizeWhereCriteria constructs result = {} and then assigns result[key] = ... for all
entries, with no guard for __proto__/constructor/prototype. OrmUtils.merge() already contains
a __proto__ safeguard, showing the project recognizes this risk; normalizeWhereCriteria should
implement the same protection (or use a null-prototype object).

src/util/OrmUtils.ts[660-703]
src/util/OrmUtils.ts[625-631]

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.normalizeWhereCriteria()` assigns arbitrary keys from a user-supplied object into a plain `{}` result. Keys like `__proto__` can mutate the object&#x27;s prototype (prototype pollution).

### Issue Context
The codebase already defends against this in `OrmUtils.merge()` by skipping `__proto__`, but the new normalization logic does not.

### Fix Focus Areas
- src/util/OrmUtils.ts[650-706]

### Implementation notes
- Add a guard at the top of the loop:
 - `if (key === &#x27;__proto__&#x27; || key === &#x27;constructor&#x27; || key === &#x27;prototype&#x27;) continue` (or throw).
- Consider constructing `result` via `Object.create(null)` and typing appropriately.
- Ensure recursive calls also return safe objects (same strategy).
- Add a unit test that passes `{ &quot;__proto__&quot;: { polluted: true } }` into normalization and asserts `({} as any).polluted` is `undefined` afterwards.

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


2. Non-plain object recursion 🐞 Bug ✓ Correctness
Description
normalizeWhereCriteria recurses into any object that isn’t an Array/Date/FindOperator. This will
incorrectly traverse non-plain objects (e.g., Buffer, RegExp, class instances used as column
values), corrupting criteria by turning those values into nested plain objects.
Code

src/util/OrmUtils.ts[R686-702]

+            } else if (
+                typeof value === "object" &&
+                !Array.isArray(value) &&
+                !(value instanceof Date) &&
+                !InstanceChecker.isFindOperator(value)
+            ) {
+                const nested = OrmUtils.normalizeWhereCriteria(
+                    value,
+                    options,
+                    propertyPath,
+                )
+                if (Object.keys(nested).length > 0) {
+                    result[key] = nested
+                }
+            } else {
+                result[key] = value
+            }
Evidence
The recursion condition in normalizeWhereCriteria is based on typeof value === "object" with only
a few exclusions. The codebase already has a plain-object check (isPlainObject) used elsewhere to
avoid recursing into non-plain objects, but normalizeWhereCriteria doesn’t use it, making it likely
to mutate legitimate scalar values that happen to be objects.

src/util/OrmUtils.ts[686-702]
src/util/OrmUtils.ts[543-550]
src/util/OrmUtils.ts[572-574]

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.normalizeWhereCriteria()` currently treats most objects as nested criteria containers. This will recurse into non-plain objects (e.g., Buffer/RegExp/custom classes) and rebuild them as plain objects, breaking where criteria for EntityManager update/delete/softDelete/restore.
### Issue Context
The same OrmUtils class already contains `isPlainObject()` and uses it in other recursion-heavy utilities to avoid descending into non-plain objects.
### Fix Focus Areas
- src/util/OrmUtils.ts[650-706]
- src/util/OrmUtils.ts[543-550]

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


3. Normalized criteria can become empty 🐞 Bug ✓ Correctness
Description
After normalization strips null/undefined keys, criteria can become {} even though the pre-check
passed, and .where({}) is rendered as WHERE 1=1, potentially updating/deleting all rows.
Code

src/entity-manager/EntityManager.ts[R842-850]

+            const normalizedCriteria = OrmUtils.normalizeWhereCriteria(
+                criteria as ObjectLiteral,
+                this.connection.options.invalidWhereValuesBehavior,
+            )
      const qb = this.createQueryBuilder()
          .update(target)
          .set(partialEntity)
-                .where(criteria)
+                .where(normalizedCriteria)
Evidence
EntityManager only rejects empty criteria *before* normalization, but then uses the normalized
result directly in .where(...). normalizeWhereCriteria can skip keys (returning {}), and
QueryBuilder explicitly renders empty condition arrays as 1=1, which turns .where({}) into a
match-all predicate.

src/entity-manager/EntityManager.ts[821-856]
src/util/OrmUtils.ts[650-706]
src/query-builder/QueryBuilder.ts[1086-1104]

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

## Issue description
`normalizeWhereCriteria()` can strip all keys from a non-empty criteria object (e.g. `{ id: undefined }` under `undefined: &amp;amp;amp;amp;amp;amp;quot;ignore&amp;amp;amp;amp;amp;amp;quot;`), producing `{}`. Passing `{}` to QueryBuilder `.where()` renders as `WHERE 1=1`, which can update/delete/softDelete/restore all rows.
### Issue Context
EntityManager currently checks `isCriteriaNullOrEmpty(criteria)` **before** normalization, but not after. QueryBuilder renders empty conditions as `1=1`.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[821-856]
- src/entity-manager/EntityManager.ts[892-931]
- src/entity-manager/EntityManager.ts[956-995]
- src/entity-manager/EntityManager.ts[1006-1045]
### Implementation notes
- After computing `normalizedCriteria`, if it is an object and `OrmUtils.isCriteriaNullOrEmpty(normalizedCriteria)` is true, reject with the same `Empty criteria(s) ... not allowed` error.
- If you also add support for array criteria (see separate finding), apply the emptiness check after filtering out empty normalized elements.

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


View more (66)
4. Array criteria normalization broken 🐞 Bug ✓ Correctness
Description
Repository methods accept FindOptionsWhere[] (OR criteria), but EntityManager now casts criteria
to ObjectLiteral and normalizes via Object.entries, which will corrupt array semantics and can
cause incorrect WHERE clauses or property-not-found errors.
Code

src/entity-manager/EntityManager.ts[R842-845]

+            const normalizedCriteria = OrmUtils.normalizeWhereCriteria(
+                criteria as ObjectLiteral,
+                this.connection.options.invalidWhereValuesBehavior,
+            )
Evidence
Repository.update/delete/softDelete/restore explicitly allow criteria arrays.
OrmUtils.isPrimitiveCriteria only treats arrays of primitives as primitive; arrays of
where-objects are not primitive and will go through normalization. normalizeWhereCriteria only
accepts an object literal and iterates Object.entries(criteria), which will treat an array as `{
'0': ..., '1': ... } and pass that object into .where(...)` instead of an array.

src/repository/Repository.ts[370-386]
src/repository/Repository.ts[440-452]
src/entity-manager/EntityManager.ts[830-850]
src/util/OrmUtils.ts[407-417]
src/util/OrmUtils.ts[650-666]

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

## Issue description
EntityManager now normalizes criteria assuming it is an object literal. But Repository APIs accept `FindOptionsWhere&amp;amp;amp;amp;amp;amp;lt;Entity&amp;amp;amp;amp;amp;amp;gt;[]` (array form for OR semantics). Arrays of object criteria are not &amp;amp;amp;amp;amp;amp;quot;primitive&amp;amp;amp;amp;amp;amp;quot; per `OrmUtils.isPrimitiveCriteria`, so they will go through normalization and be corrupted.
### Issue Context
- `Repository.update/delete/softDelete/restore` accept `FindOptionsWhere&amp;amp;amp;amp;amp;amp;lt;Entity&amp;amp;amp;amp;amp;amp;gt;[]`.
- `OrmUtils.normalizeWhereCriteria` currently accepts only `ObjectLiteral`.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[830-856]
- src/entity-manager/EntityManager.ts[914-931]
- src/entity-manager/EntityManager.ts[978-995]
- src/entity-manager/EntityManager.ts[1028-1045]
- src/util/OrmUtils.ts[650-706]
### Implementation notes
- Option A (preferred): Change `normalizeWhereCriteria` to accept `ObjectLiteral | ObjectLiteral[]` and return the same shape, mapping arrays element-wise.
- Option B: In EntityManager methods, detect `Array.isArray(criteria)` (and non-primitive) and normalize with `criteria.map(c =&amp;amp;amp;amp;amp;amp;gt; normalizeWhereCriteria(c, options))`.
- In either approach, filter out normalized `{}` elements to avoid `WHERE 1=1` OR-clauses; if the resulting array is empty, reject as empty criteria.

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


5. as any in repository tests 📘 Rule violation ✓ Correctness
Description
Additional tests introduce as any casts for repository/entity-manager criteria with nested
null/undefined. This adds type-bypass noise and reduces the value of TypeScript checks in the
suite.
Code

test/functional/null-undefined-handling/query-builders.test.ts[R164-169]

+                await connection
+                    .getRepository(Post)
+                    .delete({ text: null } as any)
     expect.fail("Expected error")
 } catch (error) {
     expect(error).to.be.instanceOf(TypeORMError)
Evidence
The rule disallows adding any casts to bypass typing; the PR adds several as any casts in
new/modified tests for delete/update criteria.

Rule 4: Remove AI-generated noise
test/functional/null-undefined-handling/query-builders.test.ts[164-206]

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

## Issue description
Repository/EntityManager tests added/modified in this PR use `as any` to bypass where-criteria typing.
## Issue Context
The tests can still validate runtime error behavior for invalid where values, but should not introduce `any` casts per the compliance rule.
## Fix Focus Areas
- test/functional/null-undefined-handling/query-builders.test.ts[164-206]

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


6. sql-null broken for writes 🐞 Bug ✓ Correctness
Description
EntityManager.update/delete/softDelete/restore validate criteria for throw-mode, but do not
transform null criteria to SQL IS NULL when invalidWhereValuesBehavior.null='sql-null'. Because
QueryBuilder.where() no longer applies this setting, writes using criteria like { field: null } will
generate "= NULL" (matches nothing) instead of matching NULL rows.
Code

src/entity-manager/EntityManager.ts[R842-848]

+            OrmUtils.validateWhereCriteria(
+                criteria as ObjectLiteral,
+                this.connection.options.invalidWhereValuesBehavior,
+            )
 const qb = this.createQueryBuilder()
     .update(target)
     .set(partialEntity)
Evidence
BaseDataSourceOptions defines 'sql-null' as transforming null to SQL NULL, but QueryBuilder now
always emits an equality predicate for non-FindOperator values (including null).
EntityManager.update forwards object criteria into QueryBuilder.where(criteria) without transforming
nulls to an IsNull()/IS NULL predicate, so 'sql-null' no longer works for these high-level write
APIs.

src/data-source/BaseDataSourceOptions.ts[216-234]
src/entity-manager/EntityManager.ts[821-850]
src/query-builder/QueryBuilder.ts[1605-1616]

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

## Issue description
`invalidWhereValuesBehavior.null = &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;sql-null&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;` no longer affects high-level write methods (EntityManager.update/delete/softDelete/restore and corresponding Repository methods). Null criteria becomes `= NULL` instead of `IS NULL`, so writes targeting NULL rows silently affect 0 rows.
### Issue Context
QueryBuilder no longer applies invalidWhereValuesBehavior in `.where()`. High-level write methods still call `.where(criteria)` directly, so they must pre-process criteria when they want to support `sql-null`.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[821-856]
- src/query-builder/QueryBuilder.ts[1598-1616]
- src/util/OrmUtils.ts[640-684]
- src/data-source/BaseDataSourceOptions.ts[216-234]
### Implementation notes
- Add a helper (e.g., `OrmUtils.normalizeWhereCriteria`) that recursively:
- converts `null` to `IsNull()` when `null===&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;sql-null&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;`
- removes `null`/`undefined` keys when behavior is `&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;ignore&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;`
- leaves `FindOperator`s intact
- only recurses into plain objects to avoid treating Buffers/Date/etc as nested criteria.
- Call it in EntityManager.update/delete/softDelete/restore before `.where(...)`.
- If normalization results in an empty object, throw an &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;Empty criteria&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot; error (same safety constraint as today).

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


7. Empty object misdetected ☑ 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


8. WHERE check leaks to SET ☑ 🐞 Bug ✓ Correctness
Description
The new undefined-handling check was added to QueryBuilder.createPropertyPath, but that method is
also used to derive UPDATE SET column paths. This can cause invalidWhereValuesBehavior (documented
for WHERE clauses) to throw or skip updates when setting relation objects, and the thrown error
message incorrectly says it occurred “of a where condition.”
Code

src/query-builder/QueryBuilder.ts[R1414-1437]

if (metadata.hasRelationWithPropertyPath(path)) {
 const relation = metadata.findRelationWithPropertyPath(path)!
+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
UpdateQueryBuilder uses QueryBuilder.createPropertyPath to compute updated columns from SET values;
the PR added invalidWhereValuesBehavior-based throwing inside createPropertyPath with an error
message explicitly about “where condition”. Docs state invalidWhereValuesBehavior applies to
operations supporting WHERE conditions, not SET values.

src/query-builder/UpdateQueryBuilder.ts[478-500]
src/query-builder/QueryBuilder.ts[1414-1434]
docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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

## Issue description
`QueryBuilder.createPropertyPath()` is used outside WHERE processing (notably UPDATE SET processing). The PR adds invalidWhereValuesBehavior-based throwing inside this shared method, which can cause UPDATE SET operations to throw a “where condition” error or skip relation updates unexpectedly.
### Issue Context
`invalidWhereValuesBehavior` is documented as applying to WHERE conditions; `UpdateQueryBuilder` uses `createPropertyPath()` to derive SET columns.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1414-1438]
- src/query-builder/UpdateQueryBuilder.ts[478-500]
- docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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


9. Empty relation object adds LEFT JOIN 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder.buildWhere no longer treats an empty relation object as “all undefined”, so it
falls through and unconditionally adds a LEFT JOIN even when the nested where produces an empty
condition. This can silently change result sets (row multiplication on to-many joins) and degrade
performance.
Code

src/query-builder/SelectQueryBuilder.ts[R4535-4557]

+                        const whereKeys = Object.keys(where[key])
+                        const undefinedKeys = whereKeys.filter(
             (k) => where[key][k] === undefined,
         )
+                        const allAllUndefined =
+                            whereKeys.length > 0 &&
+                            undefinedKeys.length === whereKeys.length
         if (allAllUndefined) {
+                            const undefinedBehavior =
+                                this.connection.options
+                                    .invalidWhereValuesBehavior?.undefined ||
+                                "ignore"
+                            if (undefinedBehavior === "throw") {
+                                // Report nested path for first undefined key
+                                const firstUndefinedKey = undefinedKeys[0]
+                                throw new TypeORMError(
+                                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                                )
+                            }
             continue
         }
     }
Evidence
The new condition whereKeys.length > 0 && ... makes allAllUndefined false for empty objects, so
the code does not continue. It then pushes a LEFT JOIN and recursively calls buildWhere on the
empty object. Because that returns an empty string, no filter is added, but the join remains and is
later applied to the final query in applyFindOptions.

src/query-builder/SelectQueryBuilder.ts[4532-4557]
src/query-builder/SelectQueryBuilder.ts[4684-4718]
src/query-builder/SelectQueryBuilder.ts[3302-3356]

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

## Issue description
`SelectQueryBuilder.buildWhere` can add a LEFT JOIN even when a nested relation condition is an empty object (or entity instance with no enumerable keys). Because the nested `buildWhere` returns an empty condition string, the join is applied without any filter, which can multiply rows for to-many relations and harm performance.
### Issue Context
Previously, `Object.keys(obj).every(...)` treated empty objects as “all undefined” and skipped the join. The new logic requires `whereKeys.length &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; 0`, so empty objects no longer short-circuit.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4532-4557]
- src/query-builder/SelectQueryBuilder.ts[4684-4718]
### Suggested change
- If `typeof where[key] === &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;object&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;`, compute `whereKeys`
- If `whereKeys.length === 0`, `continue` (skip join) because there are no predicates to apply
- Otherwise keep current `all undefined` logic (and throw when configured)
(Alternative: compute nested condition first and only add the join if the nested condition is non-empty, but be careful about deeper nested joins.)

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


10. Empty object misdetected ☑ 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


11. WHERE check leaks to SET 🐞 Bug ✓ Correctness
Description
The new undefined-handling check was added to QueryBuilder.createPropertyPath, but that method is
also used to derive UPDATE SET column paths. This can cause invalidWhereValuesBehavior (documented
for WHERE clauses) to throw or skip updates when setting relation objects, and the thrown error
message incorrectly says it occurred “of a where condition.”
Code

src/query-builder/QueryBuilder.ts[R1414-1437]

if (metadata.hasRelationWithPropertyPath(path)) {
const relation = metadata.findRelationWithPropertyPath(path)!
+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
UpdateQueryBuilder uses QueryBuilder.createPropertyPath to compute updated columns from SET values;
the PR added invalidWhereValuesBehavior-based throwing inside createPropertyPath with an error
message explicitly about “where condition”. Docs state invalidWhereValuesBehavior applies to
operations supporting WHERE conditions, not SET values.

src/query-builder/UpdateQueryBuilder.ts[478-500]
src/query-builder/QueryBuilder.ts[1414-1434]
docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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

## Issue description
`QueryBuilder.createPropertyPath()` is used outside WHERE processing (notably UPDATE SET processing). The PR adds invalidWhereValuesBehavior-based throwing inside this shared method, which can cause UPDATE SET operations to throw a “where condition” error or skip relation updates unexpectedly.
### Issue Context
`invalidWhereValuesBehavior` is documented as applying to WHERE conditions; `UpdateQueryBuilder` uses `createPropertyPath()` to derive SET columns.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1414-1438]
- src/query-builder/UpdateQueryBuilder.ts[478-500]
- docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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


12. allAllUndefined variable name 📘 Rule violation ✓ Correctness
Description
New variables named allAllUndefined appear to be a typo and deviate from consistent naming
conventions, reducing readability and maintainability. This should be renamed to a clearer, standard
form (e.g., allUndefined/areAllUndefined/allKeysUndefined).
Code

src/query-builder/QueryBuilder.ts[R1423-1425]

+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
Evidence
PR Compliance ID 1 requires new identifiers to follow established naming standards; the newly
introduced/modified identifier allAllUndefined is inconsistent and likely unintended, and it
appears in multiple new code paths.

Rule 1: Consistent Naming Conventions
src/query-builder/QueryBuilder.ts[1423-1425]
src/query-builder/SelectQueryBuilder.ts[4539-4542]

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

## Issue description
New code introduces/uses the boolean identifier `allAllUndefined`, which looks like a typo and does not follow consistent naming conventions.
## Issue Context
This identifier appears in new/modified logic for invalid where values handling. Renaming improves readability and consistency.
## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1439]
- src/query-builder/SelectQueryBuilder.ts[4535-4556]

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


13. Empty object misdetected ☑ 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


14. WHERE check leaks to SET 🐞 Bug ✓ Correctness
Description
The new undefined-handling check was added to QueryBuilder.createPropertyPath, but that method is
also used to derive UPDATE SET column paths. This can cause invalidWhereValuesBehavior (documented
for WHERE clauses) to throw or skip updates when setting relation objects, and the thrown error
message incorrectly says it occurred “of a where condition.”
Code

src/query-builder/QueryBuilder.ts[R1414-1437]

if (metadata.hasRelationWithPropertyPath(path)) {
 const relation = metadata.findRelationWithPropertyPath(path)!
+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
UpdateQueryBuilder uses QueryBuilder.createPropertyPath to compute updated columns from SET values;
the PR added invalidWhereValuesBehavior-based throwing inside createPropertyPath with an error
message explicitly about “where condition”. Docs state invalidWhereValuesBehavior applies to
operations supporting WHERE conditions, not SET values.

src/query-builder/UpdateQueryBuilder.ts[478-500]
src/query-builder/QueryBuilder.ts[1414-1434]
docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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

## Issue description
`QueryBuilder.createPropertyPath()` is used outside WHERE processing (notably UPDATE SET processing). The PR adds invalidWhereValuesBehavior-based throwing inside this shared method, which can cause UPDATE SET operations to throw a “where condition” error or skip relation updates unexpectedly.
### Issue Context
`invalidWhereValuesBehavior` is documented as applying to WHERE conditions; `UpdateQueryBuilder` uses `createPropertyPath()` to derive SET columns.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1414-1438]
- src/query-builder/UpdateQueryBuilder.ts[478-500]
- docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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


15. Empty relation object adds LEFT JOIN 🐞 Bug ✓ Correctness
Description
SelectQueryBuilder.buildWhere no longer treats an empty relation object as “all undefined”, so it
falls through and unconditionally adds a LEFT JOIN even when the nested where produces an empty
condition. This can silently change result sets (row multiplication on to-many joins) and degrade
performance.
Code

src/query-builder/SelectQueryBuilder.ts[R4535-4557]

+                        const whereKeys = Object.keys(where[key])
+                        const undefinedKeys = whereKeys.filter(
              (k) => where[key][k] === undefined,
          )
+                        const allAllUndefined =
+                            whereKeys.length > 0 &&
+                            undefinedKeys.length === whereKeys.length
          if (allAllUndefined) {
+                            const undefinedBehavior =
+                                this.connection.options
+                                    .invalidWhereValuesBehavior?.undefined ||
+                                "ignore"
+                            if (undefinedBehavior === "throw") {
+                                // Report nested path for first undefined key
+                                const firstUndefinedKey = undefinedKeys[0]
+                                throw new TypeORMError(
+                                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                                )
+                            }
              continue
          }
      }
Evidence
The new condition whereKeys.length > 0 && ... makes allAllUndefined false for empty objects, so
the code does not continue. It then pushes a LEFT JOIN and recursively calls buildWhere on the
empty object. Because that returns an empty string, no filter is added, but the join remains and is
later applied to the final query in applyFindOptions.

src/query-builder/SelectQueryBuilder.ts[4532-4557]
src/query-builder/SelectQueryBuilder.ts[4684-4718]
src/query-builder/SelectQueryBuilder.ts[3302-3356]

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

## Issue description
`SelectQueryBuilder.buildWhere` can add a LEFT JOIN even when a nested relation condition is an empty object (or entity instance with no enumerable keys). Because the nested `buildWhere` returns an empty condition string, the join is applied without any filter, which can multiply rows for to-many relations and harm performance.
### Issue Context
Previously, `Object.keys(obj).every(...)` treated empty objects as “all undefined” and skipped the join. The new logic requires `whereKeys.length &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; 0`, so empty objects no longer short-circuit.
### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4532-4557]
- src/query-builder/SelectQueryBuilder.ts[4684-4718]
### Suggested change
- If `typeof where[key] === &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;object&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;#x27;`, compute `whereKeys`
- If `whereKeys.length === 0`, `continue` (skip join) because there are no predicates to apply
- Otherwise keep current `all undefined` logic (and throw when configured)
(Alternative: compute nested condition first and only add the join if the nested condition is non-empty, but be careful about deeper nested joins.)

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


16. Empty object misdetected ☑ 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


17. WHERE check leaks to SET 🐞 Bug ✓ Correctness
Description
T...

Comment thread src/query-builder/QueryBuilder.ts Resolved
Comment thread src/query-builder/QueryBuilder.ts Resolved
@coveralls

coveralls commented Feb 13, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 74.666% (+0.02%) from 74.651%
when pulling dc1064c on fix/invalid-where-values-behavior-nested-relations
into a5c9b4c on master.

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider


Action required

1. allAllUndefined variable name 📘 Rule violation ✓ Correctness ⭐ New
Description
New variables named allAllUndefined appear to be a typo and deviate from consistent naming
conventions, reducing readability and maintainability. This should be renamed to a clearer, standard
form (e.g., allUndefined/areAllUndefined/allKeysUndefined).
Code

src/query-builder/QueryBuilder.ts[R1423-1425]

+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
Evidence
PR Compliance ID 1 requires new identifiers to follow established naming standards; the newly
introduced/modified identifier allAllUndefined is inconsistent and likely unintended, and it
appears in multiple new code paths.

Rule 1: Consistent Naming Conventions
src/query-builder/QueryBuilder.ts[1423-1425]
src/query-builder/SelectQueryBuilder.ts[4539-4542]

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

## Issue description
New code introduces/uses the boolean identifier `allAllUndefined`, which looks like a typo and does not follow consistent naming conventions.

## Issue Context
This identifier appears in new/modified logic for invalid where values handling. Renaming improves readability and consistency.

## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1439]
- src/query-builder/SelectQueryBuilder.ts[4535-4556]

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


2. Empty object misdetected 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


3. WHERE check leaks to SET 🐞 Bug ✓ Correctness
Description
The new undefined-handling check was added to QueryBuilder.createPropertyPath, but that method is
also used to derive UPDATE SET column paths. This can cause invalidWhereValuesBehavior (documented
for WHERE clauses) to throw or skip updates when setting relation objects, and the thrown error
message incorrectly says it occurred “of a where condition.”
Code

src/query-builder/QueryBuilder.ts[R1414-1437]

           if (metadata.hasRelationWithPropertyPath(path)) {
               const relation = metadata.findRelationWithPropertyPath(path)!

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
UpdateQueryBuilder uses QueryBuilder.createPropertyPath to compute updated columns from SET values;
the PR added invalidWhereValuesBehavior-based throwing inside createPropertyPath with an error
message explicitly about “where condition”. Docs state invalidWhereValuesBehavior applies to
operations supporting WHERE conditions, not SET values.

src/query-builder/UpdateQueryBuilder.ts[478-500]
src/query-builder/QueryBuilder.ts[1414-1434]
docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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

## Issue description
`QueryBuilder.createPropertyPath()` is used outside WHERE processing (notably UPDATE SET processing). The PR adds invalidWhereValuesBehavior-based throwing inside this shared method, which can cause UPDATE SET operations to throw a “where condition” error or skip relation updates unexpectedly.
### Issue Context
`invalidWhereValuesBehavior` is documented as applying to WHERE conditions; `UpdateQueryBuilder` uses `createPropertyPath()` to derive SET columns.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1414-1438]
- src/query-builder/UpdateQueryBuilder.ts[478-500]
- docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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



Remediation recommended

4. Empty JSDoc @PARAM tags 📘 Rule violation ✓ Correctness
Description
New JSDoc @param entries were added without any descriptive content, creating comment noise and
inconsistent documentation quality. This contradicts the requirement to avoid AI-like/low-value
comment additions.
Code

src/query-builder/SelectQueryBuilder.ts[R150-151]

+     * @param selection
+     * @param selectionAliasName
Evidence
PR Compliance ID 4 requires avoiding AI-generated noise such as low-value comments; the added
@param lines provide no information beyond the parameter names already present in the signature.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[147-152]

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

## Issue description
Empty JSDoc `@param` tags were added (parameter name only, no description), which adds low-value comment noise.
## Issue Context
The compliance checklist requires removing AI-generated slop/noise, including unnecessary comments. These `@param` tags do not add useful information and can be removed or rewritten with actual descriptions.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[147-152]

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


5. Validation bypass via setParameter 🐞 Bug ⛯ Reliability
Description
String-where validation only runs when parameters are passed as the second argument to
where/andWhere/orWhere. If callers set parameters later via setParameter(s), undefined/null values
can still slip through even when invalidWhereValuesBehavior.*='throw'.
Code

src/query-builder/QueryBuilder.ts[R414-442]

+    /**
+     * Validates parameters for null/undefined values based on invalidWhereValuesBehavior config.
+     * Should be called before setParameters in where/andWhere/orWhere methods.
+     */
+    protected validateWhereParameters(parameters?: ObjectLiteral): void {
+        if (!parameters) return
+
+        const nullBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
+        const undefinedBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.undefined ||
+            "ignore"
+
+        for (const [key, value] of Object.entries(parameters)) {
+            if (value === null && nullBehavior === "throw") {
+                throw new TypeORMError(
+                    `Null value encountered in parameter ':${key}' of a where condition. ` +
+                        `To match with SQL NULL, the IsNull() operator must be used. ` +
+                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                )
+            }
+            if (value === undefined && undefinedBehavior === "throw") {
+                throw new TypeORMError(
+                    `Undefined value encountered in parameter ':${key}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+        }
+    }
Evidence
SelectQueryBuilder invokes validateWhereParameters only inside where/andWhere/orWhere, but
QueryBuilder.setParameter/setParameters do not enforce invalidWhereValuesBehavior for null/undefined
values. This means .where('x = :x').setParameter('x', undefined) will bypass the new validation.

src/query-builder/SelectQueryBuilder.ts[1210-1228]
src/query-builder/QueryBuilder.ts[382-412]
src/query-builder/QueryBuilder.ts[418-441]

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 validation is easy to bypass by setting parameters after calling `where()` via `setParameter()`/`setParameters()`. This leaves undefined/null values unvalidated even with `invalidWhereValuesBehavior.* = &amp;#x27;throw&amp;#x27;`.
### Issue Context
Users commonly call `.where(&amp;#x27;...&amp;#x27;)` and then `.setParameters(...)` later. Currently, only the `where(..., parameters)` overload triggers `validateWhereParameters`.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[382-412]
- src/query-builder/QueryBuilder.ts[414-442]
- src/query-builder/SelectQueryBuilder.ts[1210-1228]

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


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (5) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Empty relation object adds LEFT JOIN 🐞 Bug ✓ Correctness ⭐ New
Description
SelectQueryBuilder.buildWhere no longer treats an empty relation object as “all undefined”, so it
falls through and unconditionally adds a LEFT JOIN even when the nested where produces an empty
condition. This can silently change result sets (row multiplication on to-many joins) and degrade
performance.
Code

src/query-builder/SelectQueryBuilder.ts[R4535-4557]

+                        const whereKeys = Object.keys(where[key])
+                        const undefinedKeys = whereKeys.filter(
                            (k) => where[key][k] === undefined,
                        )
+                        const allAllUndefined =
+                            whereKeys.length > 0 &&
+                            undefinedKeys.length === whereKeys.length
                        if (allAllUndefined) {
+                            const undefinedBehavior =
+                                this.connection.options
+                                    .invalidWhereValuesBehavior?.undefined ||
+                                "ignore"
+                            if (undefinedBehavior === "throw") {
+                                // Report nested path for first undefined key
+                                const firstUndefinedKey = undefinedKeys[0]
+                                throw new TypeORMError(
+                                    `Undefined value encountered in property '${alias}.${key}.${firstUndefinedKey}' of a where condition. ` +
+                                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                                )
+                            }
                            continue
                        }
                    }
Evidence
The new condition whereKeys.length > 0 && ... makes allAllUndefined false for empty objects, so
the code does not continue. It then pushes a LEFT JOIN and recursively calls buildWhere on the
empty object. Because that returns an empty string, no filter is added, but the join remains and is
later applied to the final query in applyFindOptions.

src/query-builder/SelectQueryBuilder.ts[4532-4557]
src/query-builder/SelectQueryBuilder.ts[4684-4718]
src/query-builder/SelectQueryBuilder.ts[3302-3356]

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

### Issue description
`SelectQueryBuilder.buildWhere` can add a LEFT JOIN even when a nested relation condition is an empty object (or entity instance with no enumerable keys). Because the nested `buildWhere` returns an empty condition string, the join is applied without any filter, which can multiply rows for to-many relations and harm performance.

### Issue Context
Previously, `Object.keys(obj).every(...)` treated empty objects as “all undefined” and skipped the join. The new logic requires `whereKeys.length &gt; 0`, so empty objects no longer short-circuit.

### Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[4532-4557]
- src/query-builder/SelectQueryBuilder.ts[4684-4718]

### Suggested change
- If `typeof where[key] === &#x27;object&#x27;`, compute `whereKeys`
- If `whereKeys.length === 0`, `continue` (skip join) because there are no predicates to apply
- Otherwise keep current `all undefined` logic (and throw when configured)

(Alternative: compute nested condition first and only add the join if the nested condition is non-empty, but be careful about deeper nested joins.)

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


2. Empty object misdetected 🐞 Bug ✓ Correctness
Description
The new “all nested relation keys undefined” logic treats empty/non-plain objects (Object.keys() ===
[]) as “all undefined”, which can wrongly skip filters or throw with a path ending in '.undefined'.
This can break valid queries when invalidWhereValuesBehavior.undefined='throw' and also changes
behavior by silently dropping relation criteria when behavior='ignore'.
Code

src/query-builder/QueryBuilder.ts[R1417-1437]

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
Both QueryBuilder.createPropertyPath and SelectQueryBuilder.buildWhere compute allAllUndefined via
undefinedKeys.length === Object.keys(obj).length, which becomes true for empty objects; then they
dereference undefinedKeys[0] without guarding, yielding an error message containing an undefined
property name or incorrectly skipping the relation.

src/query-builder/QueryBuilder.ts[1417-1437]
src/query-builder/SelectQueryBuilder.ts[4532-4555]

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 “all nested relation keys undefined” detection treats empty/non-plain objects as “all undefined” (because `Object.keys(obj).length === 0`), which can cause false-positive throws (with a `... .undefined` path) or silently skip relation filters.
### Issue Context
This logic exists in two paths:
- `QueryBuilder.createPropertyPath` (affects object-literal WHERE building)
- `SelectQueryBuilder.buildWhere` (affects find options)
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1417-1438]
- src/query-builder/SelectQueryBuilder.ts[4532-4556]

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


3. WHERE check leaks to SET 🐞 Bug ✓ Correctness
Description
The new undefined-handling check was added to QueryBuilder.createPropertyPath, but that method is
also used to derive UPDATE SET column paths. This can cause invalidWhereValuesBehavior (documented
for WHERE clauses) to throw or skip updates when setting relation objects, and the thrown error
message incorrectly says it occurred “of a where condition.”
Code

src/query-builder/QueryBuilder.ts[R1414-1437]

           if (metadata.hasRelationWithPropertyPath(path)) {
               const relation = metadata.findRelationWithPropertyPath(path)!

+                // Check if all properties of the nested relation object are undefined
+                // This handles the case when user defines conditional queries with undefined values
+                if (typeof entity[key] === "object") {
+                    const undefinedKeys = Object.keys(entity[key]).filter(
+                        (k) => entity[key][k] === undefined,
+                    )
+                    const allAllUndefined =
+                        undefinedKeys.length === Object.keys(entity[key]).length
+                    if (allAllUndefined) {
+                        const undefinedBehavior =
+                            this.connection.options.invalidWhereValuesBehavior
+                                ?.undefined || "ignore"
+                        if (undefinedBehavior === "throw") {
+                            const firstUndefinedKey = undefinedKeys[0]
+                            throw new TypeORMError(
+                                `Undefined value encountered in property '${this.alias}.${path}.${firstUndefinedKey}' of a where condition. ` +
+                                    `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                            )
+                        }
+                        // Skip this relation if behavior is 'ignore'
+                        continue
Evidence
UpdateQueryBuilder uses QueryBuilder.createPropertyPath to compute updated columns from SET values;
the PR added invalidWhereValuesBehavior-based throwing inside createPropertyPath with an error
message explicitly about “where condition”. Docs state invalidWhereValuesBehavior applies to
operations supporting WHERE conditions, not SET values.

src/query-builder/UpdateQueryBuilder.ts[478-500]
src/query-builder/QueryBuilder.ts[1414-1434]
docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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

## Issue description
`QueryBuilder.createPropertyPath()` is used outside WHERE processing (notably UPDATE SET processing). The PR adds invalidWhereValuesBehavior-based throwing inside this shared method, which can cause UPDATE SET operations to throw a “where condition” error or skip relation updates unexpectedly.
### Issue Context
`invalidWhereValuesBehavior` is documented as applying to WHERE conditions; `UpdateQueryBuilder` uses `createPropertyPath()` to derive SET columns.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1414-1438]
- src/query-builder/UpdateQueryBuilder.ts[478-500]
- docs/docs/data-source/5-null-and-undefined-handling.md[9-12]

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



Remediation recommended

4. QB tests use try/catch 📘 Rule violation ✓ Correctness ⭐ New
Description
The new QueryBuilder regression tests repeatedly use try/catch + expect.fail to assert thrown
async errors, adding unnecessary verbosity. This may violate the requirement to avoid AI-generated
noise and abnormal defensive try/catch patterns.
Code

test/functional/null-undefined-handling/query-builders.test.ts[R165-206]

+            try {
+                await connection
+                    .createQueryBuilder(Post, "post")
+                    .where("post.title = :title", { title: undefined })
+                    .getMany()
+                expect.fail("Expected error")
+            } catch (error) {
+                expect(error).to.be.instanceOf(TypeORMError)
+                expect(error.message).to.include(
+                    "Undefined value encountered in parameter ':title'",
+                )
+            }
+
+            // Test andWhere() with string and undefined parameter
+            try {
+                await connection
+                    .createQueryBuilder(Post, "post")
+                    .where("post.id > 0")
+                    .andWhere("post.title = :title", { title: undefined })
+                    .getMany()
+                expect.fail("Expected error")
+            } catch (error) {
+                expect(error).to.be.instanceOf(TypeORMError)
+                expect(error.message).to.include(
+                    "Undefined value encountered in parameter ':title'",
+                )
+            }
+
+            // Test orWhere() with string and undefined parameter
+            try {
+                await connection
+                    .createQueryBuilder(Post, "post")
+                    .where("post.id > 0")
+                    .orWhere("post.title = :title", { title: undefined })
+                    .getMany()
+                expect.fail("Expected error")
+            } catch (error) {
+                expect(error).to.be.instanceOf(TypeORMError)
+                expect(error.message).to.include(
+                    "Undefined value encountered in parameter ':title'",
+                )
+            }
Evidence
Multiple new test blocks assert promise rejection via explicit try/catch sections, which the
checklist flags as potential AI-noise/defensive style.

Rule 4: Remove AI-generated noise
test/functional/null-undefined-handling/query-builders.test.ts[165-206]

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

## Issue description
New QueryBuilder tests use repeated `try/catch` + `expect.fail` patterns for rejected promises, adding verbosity flagged by the compliance rule.

## Issue Context
The tests are validating thrown `TypeORMError` for invalid parameters; these checks can be expressed more succinctly using rejection assertions.

## Fix Focus Areas
- test/functional/null-undefined-handling/query-builders.test.ts[165-228] նրան

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


5. Upsert WHERE params unvalidated 🐞 Bug ✓ Correctness ⭐ New
Description
The new validateWhereParameters helper is not used in InsertQueryBuilder.orUpdate
overwriteCondition, so null/undefined values in those WHERE parameters can still slip through
without respecting invalidWhereValuesBehavior, making the fix incomplete for query-builder string
parameters.
Code

src/query-builder/QueryBuilder.ts[R414-442]

+    /**
+     * Validates parameters for null/undefined values based on invalidWhereValuesBehavior config.
+     * Should be called before setParameters in where/andWhere/orWhere methods.
+     */
+    protected validateWhereParameters(parameters?: ObjectLiteral): void {
+        if (!parameters) return
+
+        const nullBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
+        const undefinedBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.undefined ||
+            "ignore"
+
+        for (const [key, value] of Object.entries(parameters)) {
+            if (value === null && nullBehavior === "throw") {
+                throw new TypeORMError(
+                    `Null value encountered in parameter ':${key}' of a where condition. ` +
+                        `To match with SQL NULL, the IsNull() operator must be used. ` +
+                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                )
+            }
+            if (value === undefined && undefinedBehavior === "throw") {
+                throw new TypeORMError(
+                    `Undefined value encountered in parameter ':${key}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+        }
+    }
Evidence
The PR introduces validateWhereParameters to enforce invalidWhereValuesBehavior for query-builder
string parameters, but InsertQueryBuilder.orUpdate sets overwriteCondition parameters via
setParameters without calling validation. Docs explicitly state invalidWhereValuesBehavior applies
to all TypeORM operations supporting WHERE conditions; overwriteCondition is a WHERE clause.

src/query-builder/QueryBuilder.ts[414-442]
src/query-builder/InsertQueryBuilder.ts[378-386]
docs/docs/data-source/5-null-and-undefined-handling.md[201-205]

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

### Issue description
`InsertQueryBuilder.orUpdate(..., { overwriteCondition: { where, parameters } })` currently applies `parameters` via `setParameters()` without validating them against `invalidWhereValuesBehavior`. This leaves a gap where string-based WHERE parameters can still contain `null`/`undefined` without throwing when configured.

### Issue Context
The PR introduced `QueryBuilder.validateWhereParameters` specifically to validate query-builder where parameters before `setParameters`, but `InsertQueryBuilder.orUpdate` doesn&#x27;t use it.

### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[378-386]

### Suggested change
- Before `this.setParameters(parameters)`, add `this.validateWhereParameters(parameters)`
- Keep behavior consistent with Select/Update/Delete/SoftDelete where/andWhere/orWhere methods

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


6. Empty JSDoc @PARAM tags 📘 Rule violation ✓ Correctness
Description
New JSDoc @param entries were added without any descriptive content, creating comment noise and
inconsistent documentation quality. This contradicts the requirement to avoid AI-like/low-value
comment additions.
Code

src/query-builder/SelectQueryBuilder.ts[R150-151]

+     * @param selection
+     * @param selectionAliasName
Evidence
PR Compliance ID 4 requires avoiding AI-generated noise such as low-value comments; the added
@param lines provide no information beyond the parameter names already present in the signature.

Rule 4: Remove AI-generated noise
src/query-builder/SelectQueryBuilder.ts[147-152]

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

## Issue description
Empty JSDoc `@param` tags were added (parameter name only, no description), which adds low-value comment noise.
## Issue Context
The compliance checklist requires removing AI-generated slop/noise, including unnecessary comments. These `@param` tags do not add useful information and can be removed or rewritten with actual descriptions.
## Fix Focus Areas
- src/query-builder/SelectQueryBuilder.ts[147-152]

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


View more (1)
7. Validation bypass via setParameter 🐞 Bug ⛯ Reliability
Description
String-where validation only runs when parameters are passed as the second argument to
where/andWhere/orWhere. If callers set parameters later via setParameter(s), undefined/null values
can still slip through even when invalidWhereValuesBehavior.*='throw'.
Code

src/query-builder/QueryBuilder.ts[R414-442]

+    /**
+     * Validates parameters for null/undefined values based on invalidWhereValuesBehavior config.
+     * Should be called before setParameters in where/andWhere/orWhere methods.
+     */
+    protected validateWhereParameters(parameters?: ObjectLiteral): void {
+        if (!parameters) return
+
+        const nullBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.null || "ignore"
+        const undefinedBehavior =
+            this.connection.options.invalidWhereValuesBehavior?.undefined ||
+            "ignore"
+
+        for (const [key, value] of Object.entries(parameters)) {
+            if (value === null && nullBehavior === "throw") {
+                throw new TypeORMError(
+                    `Null value encountered in parameter ':${key}' of a where condition. ` +
+                        `To match with SQL NULL, the IsNull() operator must be used. ` +
+                        `Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in connection options to skip or handle null values.`,
+                )
+            }
+            if (value === undefined && undefinedBehavior === "throw") {
+                throw new TypeORMError(
+                    `Undefined value encountered in parameter ':${key}' of a where condition. ` +
+                        `Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in connection options to skip properties with undefined values.`,
+                )
+            }
+        }
+    }
Evidence
SelectQueryBuilder invokes validateWhereParameters only inside where/andWhere/orWhere, but
QueryBuilder.setParameter/setParameters do not enforce invalidWhereValuesBehavior for null/undefined
values. This means .where('x = :x').setParameter('x', undefined) will bypass the new validation.

src/query-builder/SelectQueryBuilder.ts[1210-1228]
src/query-builder/QueryBuilder.ts[382-412]
src/query-builder/QueryBuilder.ts[418-441]

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 validation is easy to bypass by setting parameters after calling `where()` via `setParameter()`/`setParameters()`. This leaves undefined/null values unvalidated even with `invalidWhereValuesBehavior.* = &amp;#x27;throw&amp;#x27;`.
### Issue Context
Users commonly call `.where(&amp;#x27;...&amp;#x27;)` and then `.setParameters(...)` later. Currently, only the `where(..., parameters)` overload triggers `validateWhereParameters`.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[382-412]
- src/query-builder/QueryBuilder.ts[414-442]
- src/query-builder/SelectQueryBuilder.ts[1210-1228]

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


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@naorpeled
naorpeled requested a review from alumni March 6, 2026 23:41
…e methods

- Rename validateWhereCriteria to normalizeWhereCriteria: now returns
  normalized criteria with null->IsNull() for sql-null, and strips
  null/undefined keys for ignore mode
- Fix empty relation object adding unnecessary LEFT JOIN in buildWhere
- Rename allAllUndefined typo to allUndefined
- Add tests for sql-null and ignore modes in EntityManager methods

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit b383632

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

Copy link
Copy Markdown

Persistent review updated to latest commit b383632

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

Copy link
Copy Markdown

Persistent review updated to latest commit e7debf3

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

Copy link
Copy Markdown

Persistent review updated to latest commit e7debf3

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

Copy link
Copy Markdown

Persistent review updated to latest commit 4f5d98c

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

Copy link
Copy Markdown

Persistent review updated to latest commit 4f5d98c

@sonarqubecloud

sonarqubecloud Bot commented Mar 8, 2026

Copy link
Copy Markdown

@naorpeled
naorpeled enabled auto-merge (squash) March 8, 2026 19:07
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit dc1064c

@naorpeled
naorpeled merged commit 46d5b84 into master Mar 8, 2026
39 checks passed
@naorpeled
naorpeled deleted the fix/invalid-where-values-behavior-nested-relations branch March 8, 2026 19:31
@github-actions github-actions Bot added this to the 1.0 milestone Mar 8, 2026
naorpeled added a commit to naorpeled/typeorm that referenced this pull request Mar 8, 2026
naorpeled added a commit to naorpeled/typeorm that referenced this pull request Mar 8, 2026
QB .where() is a low-level API and should not be affected by
invalidWhereValuesBehavior per PR typeorm#11878 scoping changes.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alumni alumni 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 15, 2026
…#11878)

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Giorgio Boa <[email protected]>
(cherry picked from commit 46d5b84)
alumni added a commit that referenced this pull request May 18, 2026
…#11878)

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Giorgio Boa <[email protected]>
Co-authored-by: Lucian Mocanu <[email protected]>
(cherry picked from commit 46d5b84)
@alumni alumni removed the backport This fix should be backported to a previous version label May 18, 2026
Comment thread src/util/OrmUtils.ts
}

/**
* Recursively validates an object where clause, throwing for null/undefined

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.

@naorpeled why do we need recursion?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

As far as I remember it was due to nested relations

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.

ah okay, also saw the test, i understand now :) thank you!

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.

invalidWhereValuesBehavior.undefined set to throw is not throwing when is not the only property in where

5 participants