Skip to content

fix(query-builder): reject empty where criteria on update and delete operations - #12629

Merged
alumni merged 22 commits into
masterfrom
fix/normalize-where-plain-object-proto
Jul 8, 2026
Merged

alumni merged 22 commits into
masterfrom
fix/normalize-where-plain-object-proto

Conversation

@naorpeled

@naorpeled naorpeled commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

Part of #12578

Problem

EntityManager.update / delete / softDelete / restore validate criteria for emptiness on the original input, then pass the normalized criteria to QueryBuilder.where(). Normalization can reduce a non‑empty criteria to an empty one, and an empty condition renders as WHERE 1=1 — silently turning a targeted operation into a full‑table write/delete.

Ways the criteria could collapse to empty (or otherwise produce no predicate):

  • a __proto__‑only object, e.g. JSON.parse('{"__proto__": {"polluted": true}}') → {}
  • all keys stripped under invalidWhereValuesBehavior.null/undefined = "ignore", e.g. { text: null } → {}
  • an empty OR‑branch in an array: [{}], [[]], [{ id: 1 }, {}]
  • a bare primitive mixed into an OR‑array: [1, { id: 2 }] (.where(1) has no predicate)
  • an empty entity class instance: new Post() (no set columns)

Separately, the write path passed entity class instances through normalization untouched, so invalidWhereValuesBehavior was not enforced for them — inconsistent with the read/find path (SelectQueryBuilder.buildWhere), which validates every key regardless of whether it was given a plain object or a loaded entity.

Changes

  • Validate after normalization. All four write methods now reject criteria that would produce no predicate, with the existing Empty criteria(s) are not allowed … error, instead of emitting WHERE 1=1. Covers empty objects/arrays, empty OR‑branches, bare primitives in OR‑arrays, and keyless (empty) non‑plain objects such as empty entity instances.
  • Enforce invalidWhereValuesBehavior on entity instances, exactly like plain FindOptionsWhere objects, so reads and writes behave identically. Primitive id/id‑arrays keep using whereInIds (no over‑validation), and atomic value‑types (Date, Buffer/Uint8Array) pass through untouched.
  • Guard the __proto__ key while normalizing, so a crafted criteria key can't write through the object prototype.
  • Robustness: OrmUtils.isCriteriaNullOrEmpty is a shallow, cyclic‑safe check (no unbounded recursion on self‑referential arrays).
  • Refactor: a single shared normalizeAndValidateWhereCriteria helper backs update / delete / softDelete / restore (no duplicated emptiness logic).

Unconfigured data sources are unchanged. For intentional full‑table writes, use the dedicated updateAll() / deleteAll() methods.

Behavior (invalidWhereValuesBehavior)

throw, sql-null, and ignore all work as documented for plain objects, nested plain objects, arrays, and entity instances. Any criteria that normalizes to empty is rejected rather than silently matching every row.

Tests & docs

  • Unit (test/unit/util/orm-utils.test.ts): shallow/cyclic‑safe emptiness check, __proto__ guard, entity‑instance validation, value‑type passthrough.
  • Functional (test/functional/null-undefined-handling/query-builders.test.ts): throw/sql-null/ignore across the shapes above; rejection of every empty/degenerate criteria (__proto__‑only, all‑keys‑stripped, [[]], [1, {id}], empty entity instance); entity instances validated consistently with find(). Green across the full driver matrix.
  • Docs: docs/docs/data-source/5-null-and-undefined-handling.md documents the empty‑criteria rejection and entity‑instance validation.

… __proto__

normalizeWhereCriteria() iterated any object whose criteria were being
validated, including loaded entity class instances. An entity carries all
its columns, so a nullable foreign key that happens to be null (or an unset
undefined column) could be stripped or made to throw even though those
columns are intentionally part of the WHERE condition.

Add an isPlainObject early return so entity instances (and other non-plain
objects) pass through unchanged; only plain FindOptionsWhere objects are
normalized. Also skip the __proto__ key while iterating to avoid writing
through the prototype.

This is a pure safety/structural change: the default-throw behavior for the
unconfigured case is unchanged and will be addressed separately.

Refs #12578
@github-actions github-actions Bot added the needs-triage PR needs issue link triage label Jun 26, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jun 26, 2026 •

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

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

commit: 073cb4b

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

qodo-free-for-open-source-projects Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Docs: arrays not validated 📘 Rule violation ≡ Correctness
Description
The new docs state that array criteria passed to update/delete/softDelete/restore is "passed
through untouched and is not validated", but the updated write path explicitly validates array
criteria and rejects empty OR-branches / primitive branches that would render WHERE 1=1. This can
mislead users into thinking array criteria is exempt from the new safety checks.
Code

docs/docs/data-source/5-null-and-undefined-handling.md[R250-252]

+`invalidWhereValuesBehavior` normalizes **plain `FindOptionsWhere` objects** only. Any other criteria value passed to `update` / `delete` / `softDelete` / `restore` — an **entity class instance**, a `FindOperator`, an array, a `Date`, a `Buffer`, or a primitive `id` — is passed through untouched and is **not** validated. So an entity instance whose nullable column is `null` renders as `col = NULL` (matching nothing), rather than throwing/converting. If you need null handling, pass a plain object with the `IsNull()` operator (e.g. `{ text: IsNull() }`).
+
+> Deep validation of entity-instance criteria requires entity metadata and is out of scope here; use a plain `FindOptionsWhere` object when you want `invalidWhereValuesBehavior` applied.
Evidence
The docs explicitly state that arrays are "passed through untouched" and "not validated", but the
new EntityManager.normalizeAndValidateWhereCriteria logic checks array criteria and rejects empty
arrays/empty OR-branches / primitive elements that would produce no predicate.

Rule 2: Docs updated for user-facing changes
docs/docs/data-source/5-null-and-undefined-handling.md[248-252]
src/entity-manager/EntityManager.ts[879-883]

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 docs incorrectly claim that array criteria passed to `update`/`delete`/`softDelete`/`restore` is not validated. In reality, the write criteria path now rejects array criteria that contains empty OR-branches or primitive branches that would render an always-true `WHERE 1=1`.
## Issue Context
Users may rely on this documentation to understand which criteria shapes are validated/rejected. The docs should distinguish between (a) normalization for `invalidWhereValuesBehavior` (plain objects only) and (b) safety validation that rejects empty/degenerate criteria (including arrays).
## Fix Focus Areas
- docs/docs/data-source/5-null-and-undefined-handling.md[248-252]

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


2. Bigint ID criteria rejected 🐞 Bug ≡ Correctness
Description
EntityManager.normalizeAndValidateWhereCriteria() rejects any non-object criteria that isn’t
recognized by OrmUtils.isPrimitiveCriteria, so passing a bigint id (e.g. 1n) to
update/delete/softDelete/restore now always throws. This breaks write operations for entities using
JS bigint identifiers even though other parts of the codebase explicitly accommodate bigint values.
Code

src/entity-manager/EntityManager.ts[R853-883]

+        if (OrmUtils.isPrimitiveCriteria(criteria)) {
+            if (OrmUtils.isCriteriaNullOrEmpty(criteria)) rejectEmpty()
+            return { criteria, isPrimitive: true }
+        }
+
+        const normalizedCriteria = OrmUtils.normalizeWhereCriteria(
+            criteria,
+            this.dataSource.options.invalidWhereValuesBehavior,
+        )
+
+        // On the object-criteria path, `.where()` builds a predicate only from
+        // an object's own keys. Anything else yields an empty predicate list
+        // that renders as an always-true `1=1`, so a criterion is unsafe unless
+        // it is a non-empty object. This must reject:
+        //  - primitives (a bare number/string in a mixed OR-array like
+        //    `[1, { id: 2 }]` — `.where(1)` produces no predicate),
+        //  - empty plain objects (`{}`), empty arrays (`[]`), and
+        //  - empty non-plain objects, e.g. an empty entity instance
+        //    (`new Post()`), which isCriteriaNullOrEmpty does not catch.
+        // Value-type criteria (Date, Buffer) execute via the primitive branch
+        // and never reach here.
+        const rendersNoPredicate = (value: unknown): boolean =>
+            value === null ||
+            typeof value !== "object" ||
+            Object.keys(value).length === 0
+
+        const isEmpty = Array.isArray(normalizedCriteria)
+            ? normalizedCriteria.length === 0 ||
+              normalizedCriteria.some(rendersNoPredicate)
+            : rendersNoPredicate(normalizedCriteria)
+        if (isEmpty) rejectEmpty()
Evidence
isPrimitiveCriteria currently recognizes only string/number/Date, so bigint falls into the
non-primitive path and is then rejected by rendersNoPredicate because typeof value !== "object".
The codebase also explicitly handles bigint values elsewhere (e.g., stringifying bigint parameters
for query IDs), indicating bigint is an expected runtime value type.

src/util/OrmUtils.ts[408-433]
src/entity-manager/EntityManager.ts[853-885]
src/query-builder/SelectQueryBuilder.ts[3829-3836]

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.update/delete/softDelete/restore` now route criteria through `normalizeAndValidateWhereCriteria()`. Only `string | number | Date` (and arrays of those) are considered “primitive” IDs, so `bigint` criteria is treated as non-object and rejected as empty.
### Issue Context
- Bigint is a JS primitive type commonly used for BIGINT PKs.
- Current behavior makes `manager.delete(Entity, 1n)` always fail with `Empty criteria(s)...`, which is a regression for bigint-based IDs.
### Fix Focus Areas
- src/util/OrmUtils.ts[408-433]
- src/entity-manager/EntityManager.ts[853-885]
### Suggested fix
1. Extend `OrmUtils.isSinglePrimitiveCriteria` (and therefore `isPrimitiveCriteria`) to treat `typeof criteria === "bigint"` as primitive.
2. Update the public method signatures in `EntityManager.update/delete/softDelete/restore` criteria unions to include `bigint | bigint[]` (so TS users can pass bigint without casts).
3. (Optional but recommended) Add a small functional/unit test proving `delete/update` works with bigint criteria and uses `whereInIds` branch.

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


3. Write guard misses (1=1) 🐞 Bug ≡ Correctness
Description
QueryBuilder.createWhereExpression() rejects empty write predicates only when whereExpression is
"" or exactly "1=1", but with isolateWhereStatements enabled an empty predicate can render as
"(1=1)" and bypass the guard. This can allow an unintended full-table
UPDATE/DELETE/soft-delete/restore despite the new safety check.
Code

src/query-builder/QueryBuilder.ts[R878-887]

+        const writeQueryTypes = ["update", "delete", "soft-delete", "restore"]
+        if (
+            writeQueryTypes.indexOf(this.expressionMap.queryType) !== -1 &&
+            this.expressionMap.wheres.length > 0 &&
+            (whereExpression.length === 0 || whereExpression === "1=1")
+        ) {
+            throw new TypeORMError(
+                `Empty criteria(s) are not allowed for the ${this.expressionMap.queryType} operation. ` +
+                    `To affect all rows, use the dedicated updateAll/deleteAll methods.`,
+            )
Evidence
The new write-guard only matches the literal string "1=1", but the WHERE rendering logic can wrap a
clause in parentheses when isolateWhereStatements is enabled. Since empty arrays render as "1=1",
this becomes "(1=1)" under isolation, which is still an always-true predicate but does not match the
guard condition.

src/query-builder/QueryBuilder.ts[865-892]
src/query-builder/QueryBuilder.ts[1058-1088]
src/query-builder/QueryBuilder.ts[1096-1105]
src/data-source/BaseDataSourceOptions.ts[219-223]

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 write-safety guard in `QueryBuilder.createWhereExpression()` only checks for `whereExpression === "1=1"` (or empty). When `dataSource.options.isolateWhereStatements` is enabled, `createWhereClausesExpression()` wraps each clause in parentheses, so an empty predicate becomes `(1=1)` and is not rejected. This can still generate an effectively-unfiltered WHERE for write queries.
### Issue Context
- `createWhereConditionExpression([])` returns `"1=1"` for empty arrays.
- `createWhereClausesExpression()` can wrap expressions as `("...")` when `isolateWhereStatements` is true.
- The new guard should treat `(1=1)` (and similar whitespace/parenthesis variants) as empty/always-true.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[865-892]
- src/query-builder/QueryBuilder.ts[1058-1088]
- src/query-builder/QueryBuilder.ts[1096-1105]
### Suggested implementation direction
- Replace the brittle string equality check with a robust predicate, e.g.:
- `const isTriviallyTrue = whereExpression.length === 0 || /^\(*\s*1\s*=\s*1\s*\)*$/.test(whereExpression)`
- Use the same `isTriviallyTrue` check both:
- in the write-guard (to throw), and
- in the subsequent `if (whereExpression.length > 0 && whereExpression !== "1=1")` block (so `(1=1)` is not appended as a WHERE).

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


View more (5)
4. Nested criteria yields 1=1 ✓ Resolved 🐞 Bug ≡ Correctness
Description
normalizeAndValidateWhereCriteria() only rejects criteria that are top-level empty/keyless, but it
can still accept an object/OR-branch whose nested relation value expands to zero property paths,
making QueryBuilder render an always-true WHERE 1=1. This leaves a full-table update/delete path
via inputs like { relation: new RelatedEntity() } (or similar keyless nested objects/arrays) even
after this PR’s new validation.
Code

src/entity-manager/EntityManager.ts[R869-878]

+        const rendersNoPredicate = (value: unknown): boolean =>
+            value === null ||
+            typeof value !== "object" ||
+            Object.keys(value).length === 0
+
+        const isEmpty = Array.isArray(normalizedCriteria)
+            ? normalizedCriteria.length === 0 ||
+              normalizedCriteria.some(rendersNoPredicate)
+            : rendersNoPredicate(normalizedCriteria)
+        if (isEmpty) rejectEmpty()
Evidence
The EntityManager guard only checks whether the *criteria object itself* has keys, but QueryBuilder
can still generate an empty predicate list if nested relation objects contribute no property paths;
empty predicate arrays are rendered as 1=1.

src/entity-manager/EntityManager.ts[853-878]
src/util/OrmUtils.ts[706-743]
src/query-builder/QueryBuilder.ts[1386-1474]
src/query-builder/QueryBuilder.ts[1078-1087]

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.normalizeAndValidateWhereCriteria()` only checks emptiness at the *top level* (and per OR-branch object), so it can accept criteria objects that still produce **zero predicates** after `QueryBuilder` expands relations/embeddeds.
Concrete bad shape: a criteria object with a relation key whose value is a **keyless non-plain object** (e.g. `new RelatedEntity()` with no assigned fields, or an empty relation array) can cause `QueryBuilder.createPropertyPath()` to return no paths, leading to an empty `conditions` array and rendering as `1=1`.
### Issue Context
- `QueryBuilder.createPropertyPath()` may yield **no property paths** for relation-valued keys when the nested object has no usable keys/PKs.
- `QueryBuilder.createWhereConditionExpression([])` renders `"1=1"`.
- `OrmUtils.normalizeWhereCriteria()` currently does **not** normalize/reject nested non-plain objects; it keeps them as values.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[869-878]
- src/util/OrmUtils.ts[706-743]
- src/query-builder/QueryBuilder.ts[1386-1474]
### Suggested fix direction
- Strengthen `normalizeAndValidateWhereCriteria` for object-criteria to detect and reject *nested* keyless objects/arrays that will not contribute predicates.
- At minimum: if a top-level criterion value is an object/array with `Object.keys(value).length === 0` / `value.length === 0`, reject (but **exclude** atomic/value-types and FindOperators).
- Better: add a predicate-generation-based validation (e.g., using metadata + the same property-path expansion logic) to ensure at least one predicate will be emitted for each OR-branch.
- Consider extending `OrmUtils.normalizeWhereCriteria` recursion to validate nested entity instances similarly to plain objects (while still exempting Date/Uint8Array/FindOperator).

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


5. Mixed OR yields 1=1 ✓ Resolved 🐞 Bug ⛨ Security
Description
normalizeAndValidateWhereCriteria() does not treat non-object OR-branch elements (e.g. a number) as
empty, so mixed array criteria like [1, { id: 2 }] can pass validation. QueryBuilder then
generates an empty predicate list for the primitive branch and renders it as 1=1, turning
update/delete/softDelete/restore into unfiltered operations.
Code

src/entity-manager/EntityManager.ts[R877-886]

+        const rendersNoPredicate = (value: unknown): boolean =>
+            value === null ||
+            value === undefined ||
+            value === "" ||
+            (typeof value === "object" && Object.keys(value).length === 0)
+
+        const isEmpty = Array.isArray(normalizedCriteria)
+            ? normalizedCriteria.length === 0 ||
+              normalizedCriteria.some(rendersNoPredicate)
+            : rendersNoPredicate(normalizedCriteria)
Evidence
The new emptiness validation only checks for null/undefined/"" or empty objects, so primitives
inside an OR-array are not rejected. Mixed arrays are routed to the object-criteria path (not the
primitive whereInIds path), and QueryBuilder turns an element with zero predicates into 1=1,
making the overall WHERE always true.

src/entity-manager/EntityManager.ts[859-887]
src/util/OrmUtils.ts[423-433]
src/util/OrmUtils.ts[673-700]
src/query-builder/QueryBuilder.ts[1667-1694]
src/query-builder/QueryBuilder.ts[1483-1519]
src/query-builder/QueryBuilder.ts[1078-1087]

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.normalizeAndValidateWhereCriteria()` validates array criteria (OR branches) using `rendersNoPredicate`, but it only flags `null`/`undefined`/`""`/empty-objects. Primitive array elements (e.g. `1`) are treated as non-empty and therefore allowed.
However, QueryBuilder treats such primitive OR-branch elements as producing **no predicates** (because `Object.keys(1)` is empty), and empty predicate arrays are rendered as `1=1`. This means criteria like `[1, { id: 2 }]` can result in an always-true WHERE clause and a full-table write.
## Issue Context
This affects `update`, `delete`, `softDelete`, and `restore`, all of which rely on `normalizeAndValidateWhereCriteria()`.
## Fix Focus Areas
- src/entity-manager/EntityManager.ts[877-886]
### Suggested fix approach
When `normalizedCriteria` is an array (object-criteria OR branches), enforce that **each element** is a non-null, non-array object with at least one own enumerable key.
For example:
- Add an `isValidOrBranch(value)` predicate:
- `typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0`
- Reject if any element fails this predicate.
This closes the gap for primitives (number/string/boolean), empty arrays, and other shapes that produce an empty predicate list in QueryBuilder.

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


6. Empty non-plain criteria bypass ✓ Resolved 🐞 Bug ⛨ Security
Description
When invalidWhereValuesBehavior is unset, normalizeWhereCriteria() is a no-op and
isCriteriaNullOrEmpty() only treats empty *plain* objects as empty, so a non-plain object with zero
enumerable keys (e.g., a freshly-constructed entity instance with no assigned fields) can pass
validation. QueryBuilder then derives zero predicates and renders the WHERE as 1=1, turning
update/delete/softDelete/restore into unfiltered operations.
Code

src/entity-manager/EntityManager.ts[R869-875]

+        const isEmpty = Array.isArray(normalizedCriteria)
+            ? normalizedCriteria.length === 0 ||
+              normalizedCriteria.some((element) =>
+                  OrmUtils.isCriteriaNullOrEmpty(element),
+              )
+            : OrmUtils.isCriteriaNullOrEmpty(normalizedCriteria)
+        if (isEmpty) rejectEmpty()
Evidence
The current empty-criteria check only flags empty *plain* objects; if invalidWhereValuesBehavior is
unset, normalization returns the original non-plain criteria unchanged, so an empty entity instance
is not rejected. QueryBuilder builds predicates from Object.keys(where); with zero keys, it
produces an empty condition array, which is rendered as 1=1.

src/util/OrmUtils.ts[391-399]
src/util/OrmUtils.ts[560-567]
src/util/OrmUtils.ts[664-672]
src/entity-manager/EntityManager.ts[849-878]
src/query-builder/QueryBuilder.ts[1386-1404]
src/query-builder/QueryBuilder.ts[1670-1687]
src/query-builder/QueryBuilder.ts[1078-1087]

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.normalizeAndValidateWhereCriteria()` relies on `OrmUtils.isCriteriaNullOrEmpty()` to reject empty object criteria. But `isCriteriaNullOrEmpty()` only treats empty **plain** objects as empty, so a non-plain object with **zero enumerable keys** can bypass the empty-criteria protection when `invalidWhereValuesBehavior` is not configured (because `normalizeWhereCriteria()` returns the original object unchanged).
This can lead to `.where(criteria)` producing **no predicates** and rendering as `WHERE 1=1`, which makes `update/delete/softDelete/restore` run as unfiltered writes.
### Issue Context
- The PR adds post-normalization emptiness checks, but the emptiness predicate currently misses “empty but non-plain” criteria.
- In TypeORM, a freshly constructed entity instance often has **no own enumerable keys** until fields are assigned (TS field declarations without initializers are not emitted), so this is a realistic footgun.
### Fix Focus Areas
- src/util/OrmUtils.ts[391-399]
- src/entity-manager/EntityManager.ts[849-878]
### Suggested fix
Option A (preferred): Expand `OrmUtils.isCriteriaNullOrEmpty()` so it treats **any** non-null, non-array object with `Object.keys(obj).length === 0` as empty, *except* atomic object types that should not be considered empty criteria (e.g., `Date`, `Uint8Array`/`Buffer`, and potentially FindOperators if applicable).
Option B: Add an explicit check in `normalizeAndValidateWhereCriteria()` for object criteria (and OR-branch elements) where `typeof x === 'object' && x != null && !Array.isArray(x) && Object.keys(x).length === 0`, regardless of plainness, before calling `.where()`.
Add/adjust unit/functional tests to cover `manager.delete(Entity, new Entity())` (no assigned fields) being rejected under default (unset) invalidWhereValuesBehavior.

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


7. Empty OR-branch array bypass ✓ Resolved 🐞 Bug ⛨ Security
Description
EntityManager.normalizeAndValidateWhereCriteria() relies on OrmUtils.isCriteriaNullOrEmpty(), but
that helper does not treat an empty array element as empty, so criteria like [[]] are accepted.
QueryBuilder.where([[]]) produces an empty predicate list for that branch and renders it as 1=1,
turning update/delete/softDelete/restore into unfiltered operations.
Code

src/util/OrmUtils.ts[R399-407]

+        const isValueEmpty = (value: unknown): boolean =>
+            value === undefined ||
+            value === null ||
+            value === "" ||
+            (OrmUtils.isPlainObject(value) && Object.keys(value).length === 0)
+
+        if (Array.isArray(criteria)) {
+            return criteria.length === 0 || criteria.some(isValueEmpty)
+        }
Evidence
The validator only flags array criteria as empty if it contains values that are undefined/null/"" or
an empty plain object, so an empty array element is not rejected. QueryBuilder builds OR-clauses
from array criteria, and if an element produces zero predicates (because it has no keys), the
resulting empty condition list is rendered as 1=1, creating an always-true OR-branch that matches
every row.

src/util/OrmUtils.ts[398-410]
src/util/OrmUtils.ts[674-702]
src/entity-manager/EntityManager.ts[836-852]
src/entity-manager/EntityManager.ts[866-909]
src/query-builder/QueryBuilder.ts[1624-1694]
src/query-builder/QueryBuilder.ts[1078-1087]
src/query-builder/QueryBuilder.ts[1386-1404]
src/query-builder/QueryBuilder.ts[1483-1520]

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.isCriteriaNullOrEmpty()` is used to reject criteria that would render as an always-true branch (`1=1`) in `QueryBuilder.where(...)`. The new implementation treats empty plain objects as empty, but **does not** treat an **empty array value** (e.g. `[]`) as empty.
This leaves a bypass: criteria like `[[]]` is not rejected, yet QueryBuilder will generate an empty `AND` condition list for that OR-branch, which becomes `1=1`.
### Issue Context
- `EntityManager.normalizeAndValidateWhereCriteria()` is called for update/delete/softDelete/restore and throws only if `OrmUtils.isCriteriaNullOrEmpty(normalizedCriteria)` is true.
- `QueryBuilder.createWhereConditionExpression([])` returns `"1=1"`.
- A criteria element with no enumerable keys (including an empty array) yields no predicates.
### Fix Focus Areas
- src/util/OrmUtils.ts[398-410]
### Suggested fix
1. Extend `isValueEmpty` to treat empty arrays as empty:
- Add `(Array.isArray(value) && value.length === 0)` to the emptiness predicate.
2. Add unit coverage (and/or functional coverage) for `isCriteriaNullOrEmpty([[]]) === true` and for rejecting `delete/update` with criteria `[[]]` (or equivalent) to prevent regressions.

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


8. Empty where becomes 1=1 ✓ Resolved 🐞 Bug ⛨ Security
Description
OrmUtils.normalizeWhereCriteria() can drop keys (including the new unconditional __proto__ skip)
and return {}, but EntityManager.update/delete/softDelete/restore only validate emptiness
*before* normalization. The empty normalized criteria then flows into QueryBuilder.where({}),
which renders an empty condition array as 1=1, resulting in an unfiltered write/delete.
Code

src/util/OrmUtils.ts[R689-692]

const result: ObjectLiteral = {}
for (const [key, value] of Object.entries(criteria)) {
+            if (key === "__proto__") continue
const propertyPath = path ? `${path}.${key}` : key
Evidence
The PR change explicitly skips __proto__ during normalization, which can produce an empty {};
the EntityManager methods do not validate the post-normalization output; and QueryBuilder renders
empty condition arrays as 1=1, yielding an unfiltered WHERE clause.

src/util/OrmUtils.ts[660-729]
src/entity-manager/EntityManager.ts[852-887]
src/entity-manager/EntityManager.ts[938-963]
src/query-builder/QueryBuilder.ts[1078-1087]

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()` can normalize a previously non-empty criteria object into an empty object (e.g., when the only enumerable key is `"__proto__"`, which is now skipped). `EntityManager.update/delete/softDelete/restore` validate emptiness only on the *original* criteria and then pass the normalized output to `QueryBuilder.where()`. An empty normalized criteria becomes an empty condition array and is rendered as `WHERE 1=1`, turning the operation into an unfiltered write.
### Issue Context
This is high-impact because it can turn a targeted operation into a full-table update/delete. A minimal reproduction shape is:
- `criteria = JSON.parse('{"__proto__": {"polluted": true}}')`
- `normalizedCriteria` becomes `{}` due to the `__proto__` skip
- `.where({})` produces `WHERE 1=1`
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[837-1081]
- src/util/OrmUtils.ts[660-729]
- src/query-builder/QueryBuilder.ts[1078-1087]
### Suggested remediation
1. After calling `OrmUtils.normalizeWhereCriteria(...)`, re-check the **normalized** criteria for emptiness:
- For object criteria: `OrmUtils.isCriteriaNullOrEmpty(normalizedCriteria)`
- For array criteria: ensure it’s not `[]` and that it doesn’t contain any empty objects (e.g. `every(c => OrmUtils.isCriteriaNullOrEmpty(c))`), otherwise reject.
2. If the normalized criteria is empty, reject with a `TypeORMError` similar to the existing “Empty criteria(s) are not allowed …” errors.
3. (Optional hardening) Consider throwing immediately when encountering a `"__proto__"` key instead of silently dropping it, to avoid turning a non-empty user input into an empty filter.

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



Remediation recommended

9. Uint8Array criteria misrouted 🐞 Bug ≡ Correctness
Description
EntityManager.normalizeAndValidateWhereCriteria only treats string/number/Date as “primitive” ID
criteria, so Buffer/Uint8Array criteria falls into the object .where() path. QueryBuilder then
iterates byte indices ("0", "1", …) as property paths and throws EntityPropertyNotFoundError (or
produces invalid predicates), breaking update/delete/softDelete/restore for binary IDs.
Code

src/entity-manager/EntityManager.ts[R853-856]

+        if (OrmUtils.isPrimitiveCriteria(criteria)) {
+            if (OrmUtils.isCriteriaNullOrEmpty(criteria)) rejectEmpty()
+            return { criteria, isPrimitive: true }
+        }
Evidence
The write methods branch to whereInIds only when isPrimitiveCriteria is true; binary types are
not considered primitive, but the normalizer explicitly treats them as atomic and returns them
unchanged. QueryBuilder’s object-criteria path derives property paths from Object.keys(...), so a
Uint8Array/Buffer yields numeric keys that don’t match entity columns and triggers
EntityPropertyNotFoundError.

src/entity-manager/EntityManager.ts[853-886]
src/util/OrmUtils.ts[408-433]
src/util/OrmUtils.ts[689-747]
src/query-builder/QueryBuilder.ts[1369-1377]
src/query-builder/QueryBuilder.ts[1386-1405]

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.normalizeAndValidateWhereCriteria()` chooses between `whereInIds()` and `where()` using `OrmUtils.isPrimitiveCriteria()`, which currently recognizes only `string | number | Date`. Meanwhile, `OrmUtils.normalizeWhereCriteria()` explicitly treats `Uint8Array`/`Buffer` as atomic and returns them unchanged. This combination allows `Uint8Array`/`Buffer` criteria to flow into the object-criteria `.where(...)` path, where QueryBuilder interprets numeric byte indices as entity property names and fails.
## Issue Context
TypeORM now documents/tests “atomic value-types (Date, Buffer/Uint8Array) pass through untouched”, but the write-path primitive/object routing still excludes binary types.
## Fix Focus Areas
- src/util/OrmUtils.ts[408-433]
- src/common/PrimitiveCriteria.ts[1-5]
- src/entity-manager/EntityManager.ts[853-886]
## Suggested fix
1. Extend `SinglePrimitiveCriteria` / `PrimitiveCriteria` to include binary IDs (prefer `Uint8Array`, which covers Node `Buffer`).
2. Update `OrmUtils.isSinglePrimitiveCriteria()` to return true for `isUint8Array(criteria)`.
3. (Optional safety) Add a targeted assertion in `normalizeAndValidateWhereCriteria` that if `isUint8Array(criteria)` then it must be treated as primitive and routed to `whereInIds`, preventing accidental `.where()` usage.

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


10. Write null/undef default mismatch ✓ Resolved 🐞 Bug ≡ Correctness
Description
EntityManager update/delete/softDelete/restore pass dataSource.options.invalidWhereValuesBehavior
into OrmUtils.normalizeWhereCriteria(), but when that option is unset the normalizer returns
criteria unchanged—so null/undefined can reach QueryBuilder and become col = NULL or an
undefined-parameter error instead of throwing. This diverges from the read/find path, which defaults
missing invalidWhereValuesBehavior to "throw", and from the docs describing default throwing for
high-level APIs.
Code

src/entity-manager/EntityManager.ts[R853-856]

+        const normalizedCriteria = OrmUtils.normalizeWhereCriteria(
+            criteria,
+            this.dataSource.options.invalidWhereValuesBehavior,
+        )
Evidence
EntityManager forwards the (optional) invalidWhereValuesBehavior config into
OrmUtils.normalizeWhereCriteria; that helper returns early when the option is unset, while
SelectQueryBuilder defaults missing options to "throw" and the docs state default throwing applies
to EntityManager methods too.

src/entity-manager/EntityManager.ts[853-856]
src/util/OrmUtils.ts[668-675]
src/query-builder/SelectQueryBuilder.ts[4350-4375]
docs/docs/data-source/5-null-and-undefined-handling.md[5-7]

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

## Issue description
Write-path criteria normalization is skipped when `invalidWhereValuesBehavior` is unset, so `null`/`undefined` can flow into `QueryBuilder` from EntityManager mutations, diverging from the read/find path’s default-throw behavior and the docs.
### Issue Context
- `SelectQueryBuilder.buildWhere()` treats a missing `invalidWhereValuesBehavior` as `"throw"` via `?.x ?? "throw"`.
- `OrmUtils.normalizeWhereCriteria()` returns early when `options` is falsy, so EntityManager write methods won’t throw on `null`/`undefined` unless the option is explicitly provided.
### Fix Focus Areas
- src/entity-manager/EntityManager.ts[853-856]
- src/util/OrmUtils.ts[668-675]
- src/query-builder/SelectQueryBuilder.ts[4350-4375]
- docs/docs/data-source/5-null-and-undefined-handling.md[5-7]
### Suggested fix direction
- Make EntityManager write-path normalization enforce the same default as the read path:
- Option A: change `OrmUtils.normalizeWhereCriteria` to treat `options === undefined` as `{}` (so default behavior remains `throw`).
- Option B: have EntityManager pass `{}` when `dataSource.options.invalidWhereValuesBehavior` is undefined.
- Add/adjust a functional test demonstrating that `manager.delete(Entity, { col: null })` throws by default (no explicit invalidWhereValuesBehavior set), matching `find*()` behavior.

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


11. Unsound criteria return types ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
OrmUtils.normalizeWhereCriteria() is typed to return only ObjectLiteral/ObjectLiteral[] but now
returns primitives/atomic values (e.g., Date/Uint8Array) unchanged, and
EntityManager.normalizeAndValidateWhereCriteria() similarly models criteria as object-only even
when isPrimitive is true. This makes it easy for future callers to accidentally treat returned
criteria as an object (e.g., call Object.keys / pass to .where) without TypeScript flagging the
mismatch.
Code

src/util/OrmUtils.ts[R693-700]

+        if (
+            criteria === null ||
+            typeof criteria !== "object" ||
+            criteria instanceof Date ||
+            isUint8Array(criteria)
+        ) {
+            return criteria
+        }
Evidence
The implementation explicitly returns criteria when it’s not an object or is an atomic value-type,
but the function signature still promises only object criteria; unit tests also assert passthrough
for primitives/atomic types. EntityManager’s helper returns criteria in the primitive branch but
its return type still constrains criteria to object-only, weakening type safety.

src/util/OrmUtils.ts[664-701]
test/unit/util/orm-utils.test.ts[316-330]
src/entity-manager/EntityManager.ts[849-862]

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()` and `EntityManager.normalizeAndValidateWhereCriteria()` have TypeScript signatures that claim they return only object-shaped criteria (`ObjectLiteral | ObjectLiteral[]`), but the implementation can return non-object/atomic values (e.g., `Date`, `Uint8Array`, primitives) unchanged. This creates unsound typings and can mislead future code into treating returned criteria as an object.
### Issue Context
The PR intentionally adds passthrough behavior for primitives/atomic value-types, but the exposed types were not updated to match.
### Fix Focus Areas
- src/util/OrmUtils.ts[664-743]
- src/entity-manager/EntityManager.ts[849-892]
- test/unit/util/orm-utils.test.ts[316-330]
### Suggested fix
- Update `OrmUtils.normalizeWhereCriteria` with overloads (or a widened union return type) so the signature matches runtime behavior.
- Example direction: overloads for `(criteria: ObjectLiteral|ObjectLiteral[]) => ObjectLiteral|ObjectLiteral[]` and a broader `(criteria: unknown) => unknown`, or explicitly return `ObjectLiteral | ObjectLiteral[] | PrimitiveCriteria | Date | Uint8Array | null`.
- Update `EntityManager.normalizeAndValidateWhereCriteria` to accept the same `criteria` union as the public methods and return `criteria` as `PrimitiveCriteria | ObjectLiteral | ObjectLiteral[]` (keyed by `isPrimitive`) to eliminate unsafe casts and preserve type safety.
- Adjust tests as needed to align with the new type contracts (no runtime behavior change required).

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


View more (4)
12. Docs use wrong signatures 🐞 Bug ⚙ Maintainability
Description
The new docs example calls manager.findBy(post) and manager.delete(post) with a single argument,
but EntityManager.findBy and EntityManager.delete both require the entity target/class as the
first argument. Copy-pasting this snippet will not compile/run and misleads users about how to pass
entity instances as criteria.
Code

docs/docs/data-source/5-null-and-undefined-handling.md[R258-259]

+await manager.findBy(post) // throws "Null value encountered..."
+await manager.delete(post) // also throws — consistent with the read path
Evidence
The docs snippet shows single-argument calls, but the actual EntityManager method signatures require
two arguments: the entity target/class and the criteria/where object.

docs/docs/data-source/5-null-and-undefined-handling.md[248-260]
src/entity-manager/EntityManager.ts[1253-1264]
src/entity-manager/EntityManager.ts[959-982]

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 documentation snippet under “Entity class instances are validated too” shows `manager.findBy(post)` and `manager.delete(post)`, but the actual `EntityManager` methods require the entity target as the first parameter.
## Issue Context
- `EntityManager.findBy(entityClass, where)` requires the entity target/class first.
- `EntityManager.delete(targetOrEntity, criteria)` requires the entity target/class first.
## Fix Focus Areas
- docs/docs/data-source/5-null-and-undefined-handling.md[248-262]
## Suggested change
Update the snippet to something like:

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


13. Primitive arrays over-validated ✓ Resolved 🐞 Bug ≡ Correctness
Description
EntityManager.update/delete/softDelete/restore normalize+validate criteria before checking
isPrimitiveCriteria, so primitive ID arrays are subjected to OrmUtils.isCriteriaNullOrEmpty()’s
per-element “empty” rules. This can reject non-empty IN-clause criteria (e.g. a string-ID list
containing ""), and it adds an O(n) normalizeWhereCriteria() map over large ID lists even though the
primitive branch uses whereInIds(criteria) and ignores the normalized result.
Code

src/entity-manager/EntityManager.ts[R881-887]

+        const normalizedCriteria = this.normalizeAndValidateWhereCriteria(
+            criteria as ObjectLiteral | ObjectLiteral[],
+            "update",
+        )
if (OrmUtils.isPrimitiveCriteria(criteria)) {
const qb = this.createQueryBuilder()
Evidence
The PR moved normalization/validation ahead of the primitive-criteria check, so arrays intended for
whereInIds are now validated as if they were OR-branches; at the same time,
isCriteriaNullOrEmpty treats "" as empty and flags arrays with any empty element as empty. But
primitive arrays are executed via whereInIds(ids), which does not create an OR branch that can
render as 1=1, so this validation is not necessary for safety and can block valid calls.

src/entity-manager/EntityManager.ts[866-908]
src/util/OrmUtils.ts[382-410]
src/util/OrmUtils.ts[674-692]
src/query-builder/WhereExpressionBuilder.ts[108-118]

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

## Issue description
`normalizeAndValidateWhereCriteria()` is invoked before the `isPrimitiveCriteria()` branch, which means primitive criteria arrays (used by `whereInIds`) are evaluated with the same “array element emptiness” semantics intended for OR-style `where: ObjectLiteral[]`.
This can incorrectly reject non-empty primitive criteria arrays (e.g. arrays containing an empty string), and it needlessly normalizes/maps large ID lists although the `whereInIds` path doesn’t use `normalizedCriteria`.
## Issue Context
- `EntityManager.update/delete/softDelete/restore` all call `normalizeAndValidateWhereCriteria(...)` unconditionally.
- `OrmUtils.isCriteriaNullOrEmpty` considers an array empty if **any** element is empty, and “empty” includes `""`.
## Fix Focus Areas
- src/entity-manager/EntityManager.ts[836-908]
- src/entity-manager/EntityManager.ts[946-975]
- src/util/OrmUtils.ts[398-409]
### Suggested approach
1. Check `OrmUtils.isPrimitiveCriteria(criteria)` **before** normalization.
2. For primitive criteria:
- validate emptiness with primitive-specific rules (e.g., `[]` is empty; decide explicitly whether `""` should be allowed rather than inheriting OR-array semantics),
- skip `normalizeWhereCriteria()` entirely.
3. Only run `normalizeWhereCriteria()` + post-normalization emptiness check for non-primitive object criteria (`ObjectLiteral` or `ObjectLiteral[]`).

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


14. Cyclic array stack overflow ✓ Resolved 🐞 Bug ☼ Reliability
Description
OrmUtils.isCriteriaNullOrEmpty() now recursively traverses array elements and will recurse
infinitely on self-referential (cyclic) arrays, throwing a RangeError during EntityManager
update/delete/softDelete/restore criteria validation.
Code

src/util/OrmUtils.ts[R395-402]

+        if (Array.isArray(criteria)) {
+            return (
+                criteria.length === 0 ||
+                criteria.some((element) =>
+                    OrmUtils.isCriteriaNullOrEmpty(element),
+                )
+            )
+        }
Evidence
The new array branch in isCriteriaNullOrEmpty recursively calls itself on each element with no
cycle detection. EntityManager’s new normalizeAndValidateWhereCriteria always calls this emptiness
check on user-provided criteria for update/delete/softDelete/restore, so a cyclic array input will
trigger unbounded recursion and stack overflow before any query executes.

src/util/OrmUtils.ts[394-403]
src/entity-manager/EntityManager.ts[836-851]

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.isCriteriaNullOrEmpty()` now recursively inspects arrays (`some(element => isCriteriaNullOrEmpty(element))`). For cyclic arrays (e.g., `const a:any[]=[]; a.push(a)`), this causes infinite recursion and a `RangeError: Maximum call stack size exceeded` during criteria validation.
### Issue Context
`EntityManager.normalizeAndValidateWhereCriteria()` calls `OrmUtils.isCriteriaNullOrEmpty(normalizedCriteria)` for `update/delete/softDelete/restore`, so the crash is reachable from these public APIs when a cyclic criteria array is passed.
### Fix Focus Areas
- src/util/OrmUtils.ts[395-403]
- src/entity-manager/EntityManager.ts[836-851]
### Suggested fix approach
- Add cycle detection to `isCriteriaNullOrEmpty` for arrays (and optionally objects) using a `WeakSet<object>` (or `Set<any>` if you need to support primitives too).
- If an already-seen array is encountered, either:
- treat it as **not empty** (to avoid false “empty” detection), or
- throw a `TypeORMError` like `Circular criteria is not supported` (clearer than RangeError).
- Keep current semantics for non-cyclic arrays (length==0 or contains empty element => empty).

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


15. Entity null bypasses sql-null ✓ Resolved 🐞 Bug ≡ Correctness
Description
OrmUtils.normalizeWhereCriteria now returns non-plain objects (including entity instances)
unchanged, so null/undefined values bypass invalidWhereValuesBehavior for
EntityManager.delete/update/softDelete/restore. Those values then flow into QueryBuilder.where()
which builds = predicates (no null special-casing), potentially turning intended operations into
silent no-ops (e.g., col = NULL) or driver errors for undefined.
Code

src/util/OrmUtils.ts[R685-687]

+        if (!OrmUtils.isPlainObject(criteria)) {
+            return criteria
+        }
Evidence
The PR adds an early return that skips normalization for non-plain objects; update/delete operations
feed the returned criteria directly into QueryBuilder.where(). QueryBuilder then renders
equality as = even for null values, so bypassing normalization removes the only place where null
can be converted to IsNull() or rejected on this code path.

src/util/OrmUtils.ts[660-729]
src/entity-manager/EntityManager.ts[947-963]
src/query-builder/QueryBuilder.ts[1618-1622]
src/query-builder/QueryBuilder.ts[1117-1121]
test/functional/null-undefined-handling/query-builders.test.ts[240-257]

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()` now early-returns for non-plain objects (entity instances), which disables `invalidWhereValuesBehavior` enforcement/conversion on the update/delete query path. Since `QueryBuilder` renders equality as `col = :param` even when `param` is `null`, this can silently produce non-matching predicates (`= NULL`) or undefined-bound parameters.
## Issue Context
- `EntityManager.delete()` (and update/softDelete/restore) always calls `OrmUtils.normalizeWhereCriteria(...)` before passing the criteria to `.where(...)`.
- `QueryBuilder.getWherePredicateCondition()` returns an `equal` operator for non-FindOperator values, and `createWhereConditionExpression()` renders it as `=` with no null special-case.
## Fix Focus Areas
- src/util/OrmUtils.ts[660-730]
- src/entity-manager/EntityManager.ts[947-963]
- src/query-builder/QueryBuilder.ts[1618-1622]
- src/query-builder/QueryBuilder.ts[1117-1121]
- test/functional/null-undefined-handling/query-builders.test.ts[240-257]
## Suggested fix approach
1. Strengthen the functional test to assert the delete actually affects a row (e.g., check `DeleteResult.affected === 1` or verify the row is gone).
2. Decide and implement the intended semantics for entity-instance criteria with null/undefined on update/delete paths. Options include:
- Apply a limited normalization pass to non-plain objects for null-handling only (e.g., convert `null` to `IsNull()` when `invalidWhereValuesBehavior.null === 'sql-null'`), or
- Explicitly document/guard against passing entity instances with nullable columns as criteria on update/delete paths, or
- Add a targeted null-handling path in the query-building for update/delete object criteria (careful: can be breaking).
3. Ensure behavior matches the config expectations for `invalidWhereValuesBehavior` in the update/delete path (even if entity instances are exempt from throwing, they should not silently generate non-matching SQL).

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


Grey Divider

  • Author self-review: I have...

Address review feedback on the new tests:

- __proto__ guard test now asserts the returned object's own prototype is
  still Object.prototype (per-object prototype mutation), not only that the
  global Object.prototype is unpolluted — the prior check passed even without
  the guard.

- Entity-instance passthrough test now asserts observable effects: a fully
  populated instance deletes its row, and an instance with a null nullable
  column does not throw and leaves the row in place (it renders as
  'text = NULL', which matches nothing; IsNull() is required to match SQL
  NULL). This documents that passthrough never silently validates the
  instance and shows the actual query effect.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Thanks @qodo — addressed both findings in 933c154 (tests only; the production behavior is intentional and unchanged):

2. __proto__ test misses prototype — fixed. The test now asserts on the returned object rather than a fresh literal:

expect(Object.getPrototypeOf(result)).to.equal(Object.prototype)
expect(result.polluted).to.equal(undefined)

Without the if (key === "__proto__") continue guard, result["__proto__"] = … re-points the returned object's prototype, so this now fails if the guard is removed (the old ({}).polluted check passed regardless).

1. Entity null bypasses sql-null — the passthrough is intentional and matches find() semantics: an entity class instance is not validated against invalidWhereValuesBehavior. Its set columns are passed straight to .where(entity), exactly as before this PR for the unconfigured case — passing an instance with a null column already rendered = NULL on master. This PR only stops a configured throw from firing on instances; it doesn't introduce the = NULL rendering, and deeper null-handling for entity criteria (e.g. auto-IsNull()) is out of scope here.

That said, the functional test was too weak (asserted only "no throw"). I strengthened it to assert observable effects, per your suggestion:

  • a fully-populated instance deletes its row (findOneBy(...) → null);
  • an instance with a null nullable column does not throw and leaves the row in place — documenting that text = NULL matches nothing and IsNull() is required to match a SQL NULL.

Thanks — this addresses both findings well.

  • finding 1: the passthrough behavior is now clearly documented as intentional, and the updated test verifies the observable behavior rather than just “no throw”.
  • finding 2: the prototype-pollution test is now correctly asserting on the returned object, so it will fail if the __proto__ guard is removed.

No further concerns from my side.

@naorpeled naorpeled added linked-issue PR references an issue and removed needs-triage PR needs issue link triage labels Jun 26, 2026
@github-actions github-actions Bot added needs-triage PR needs issue link triage and removed linked-issue PR references an issue labels Jun 26, 2026
alumni
alumni previously approved these changes Jun 28, 2026
@alumni alumni added backport This fix should be backported to a previous version and removed needs-triage PR needs issue link triage labels Jun 28, 2026
@KODEXFV

KODEXFV commented Jun 28, 2026

Copy link
Copy Markdown

Noting one scope gap for #12578: this PR body says the unconfigured default behavior is intentionally untouched, and the new unit test currently asserts OrmUtils.normalizeWhereCriteria(criteria) returns the same object when options is omitted.

That means the original #12578 path still remains for unconfigured data sources: EntityManager.update/delete/softDelete/restore pass this.dataSource.options.invalidWhereValuesBehavior, so with no configured option normalizeWhereCriteria() still returns { text: null } / { text: undefined } unchanged instead of applying the documented default throw behavior.

If the default-behavior follow-up lands separately, two edge cases from the duplicate PRs are worth carrying forward with it:

  • after normalization, write criteria that become {} or contain an empty OR branch should be rejected before .where(...), otherwise ignore can turn a scoped write into a broad one;
  • once the early return is removed, malformed top-level OR entries like [null] / [undefined] should throw a controlled TypeORMError instead of leaking TypeError: Cannot convert undefined or null to object.

Happy to help turn those into a smaller follow-up patch if useful.

normalizeWhereCriteria can reduce a non-empty criteria object to {} (e.g.
a "__proto__"-only object whose key is skipped by the pollution guard, or
all keys stripped under invalidWhereValuesBehavior: "ignore"). update/
delete/softDelete/restore validated emptiness only on the original criteria,
so the normalized {} reached .where(), rendered as "WHERE 1=1", and turned a
targeted write into a full-table one.

Re-check the normalized criteria via new OrmUtils.isNormalizedWhereCriteriaEmpty
(also rejects arrays that are empty or contain any empty OR-branch) and reject
with the existing "Empty criteria(s) are not allowed" error.
Comment thread src/util/OrmUtils.ts Outdated
*
* @param criteria
*/
public static isNormalizedWhereCriteriaEmpty(

@alumni alumni Jul 1, 2026 •

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.

isNormalizedWhereCriteriaEmpty looks like a duplicate of isCriteriaNullOrEmpty (with a bug in that function fixed).

Comment thread src/entity-manager/EntityManager.ts Outdated
// normalization may have stripped every key (e.g. a "__proto__"-only
// object, or all keys removed under the "ignore" behavior); a now-empty
// criteria would render as "WHERE 1=1" and update the whole table.
if (OrmUtils.isNormalizedWhereCriteriaEmpty(normalizedCriteria)) {

@alumni alumni Jul 1, 2026 •

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.

I wonder what's the point of checking if the criteria is empty TWICE. We probably don't do it right the first time 😉 Or we don't do it at the right time 😉😉

@michaelbromley

Copy link
Copy Markdown
Member

He @naor, I had my custom review agent Nigel look at this and something was flagged that is worth checking to see if it is a legit concern, as it might contradict this earlier defense:

Entity null bypasses sql-null — the passthrough is intentional and matches find() semantics: an entity class instance is not validated against invalidWhereValuesBehavior.

Nigel’s review findings TypeORM lets you configure what happens when a null or undefined sneaks into a query's WHERE conditions. You set it once on your connection:

invalidWhereValuesBehavior: { null: "throw", undefined: "throw" }

"throw" means: "if someone tries to filter by a null/undefined value, stop and raise an error instead of silently building a broken query." This exists because column = NULL in SQL matches nothing (you have to write column IS NULL), so a stray null usually means a bug — better to shout than to silently return/delete the wrong rows.

The trap: this rule is enforced in two separate places

Here's the thing most people (including the PR author and the reviewer who approved it) didn't realise. There isn't one piece of code that enforces this setting. There are two completely separate copies, one for each family of operations:

┌───────────────────────────────────────────────────┬──────────────────────────────────────────────────────────┐
│                    You call...                    │                 Enforcement lives in...                  │
├───────────────────────────────────────────────────┼──────────────────────────────────────────────────────────┤
│ find(), findBy(), findOne() (reading rows)        │ SelectQueryBuilder.buildWhere() —                        │
│                                                   │ SelectQueryBuilder.ts:4354 onwards                       │
├───────────────────────────────────────────────────┼──────────────────────────────────────────────────────────┤
│ update(), delete(), softDelete(), restore()       │ OrmUtils.normalizeWhereCriteria() — OrmUtils.ts          │
│ (writing/removing rows)                           │                                                          │
└───────────────────────────────────────────────────┴──────────────────────────────────────────────────────────┘

Two hand-written implementations of the same idea. They already had slightly different wording and logic before this PR ever showed up.

What the PR changed

The PR added an escape hatch to the write copy only (normalizeWhereCriteria). The new rule: "if the thing you're filtering by is a loaded entity object (not a plain {...}), skip all the null/undefined checking — pass it straight through untouched."

// the new early-return in normalizeWhereCriteria
if (!OrmUtils.isPlainObject(criteria)) {
    return criteria     // entity instances bypass all validation
}

The justification the author gave — and why it's wrong

When a review bot flagged this, the author defended it (in the PR comments) by saying:

▎ "the passthrough is intentional and matches find() semantics: an entity class instance is not validated against invalidWhereValuesBehavior."

In plain English: "Don't worry, the read side (find()) already ignores entities like this, so I'm just matching existing behaviour."

That claim is false. I read the read-side code. Here's the actual loop from SelectQueryBuilder.buildWhere (SelectQueryBuilder.ts:4353-4398):

for (const key in where) {          // ← iterates EVERY key
    let parameterValue = where[key]
    ...
    if (parameterValue === undefined) {
        ... ?? "throw" ...          // throws unless you opted out
    }
    if (parameterValue === null) {
        ... "throw" ...             // throws unless you opted out
    }
}

There is no "is this a plain object or an entity?" check anywhere in here. The read side validates every key of whatever you pass it — plain object or loaded entity, it makes no difference. So find() does not have the behaviour the author claims to be matching.

The concrete consequence

Say you've got invalidWhereValuesBehavior: { null: "throw" } configured, and a loaded Post entity whose nullable text column happens to be null:

const post = await repo.findOneBy({ id: 5 })   // post.text === null

// READ path — validated, so it throws loudly:
await repo.findBy(post)          // ❌ throws "Null value encountered..."

// WRITE path AFTER this PR — bypassed, so it stays silent:
await repo.delete(post)          // 😶 no error — builds `text = NULL`,
                                 //    matches zero rows, deletes nothing

Same input, same setting, opposite behaviour depending on whether you're reading or writing. The whole point of a "throw" setting is that it fires consistently. After this PR it fires on reads but goes quiet on writes — and the person configured "throw" precisely because they wanted to be warned.

Why this matters beyond the one bug

The deeper issue Nigel is pointing at: the same rule living in two copies that are now actively drifting apart. Nobody reading normalizeWhereCriteria next to buildWhere will understand why the identical setting produces different results for the identical input — because the divergence isn't documented, it's accidental.

What "fix" means here

The minimum bar is honesty in the reasoning: the passthrough might be defensible as "this matches the low-level, unvalidated QueryBuilder.where() behaviour" — but not as "matches find()." Either correct that justification, or reconsider whether the bypass should exist at all. The cleaner long-term answer is one shared validation helper feeding both paths, so this class of "two copies drift" bug can't recur — but that's a bigger change worth its own follow-up.

naorpeled added 3 commits July 3, 2026 16:40
…lization

Address review feedback: fold the array-aware emptiness logic into
isCriteriaNullOrEmpty (an array is empty if it has no elements or any empty
element) and drop the near-duplicate isNormalizedWhereCriteriaEmpty helper.

Each of update/delete/softDelete/restore now normalizes first and checks
emptiness once on the normalized criteria, instead of validating the original
criteria and re-validating the normalized output. Behavior is unchanged for
callers not using invalidWhereValuesBehavior (normalize is a passthrough).
Reduce duplication flagged by SonarCloud (new_duplicated_lines_density):
the identical normalize + empty-check + reject block was copy-pasted across
update/delete/softDelete/restore. Extract it into a single
normalizeAndValidateWhereCriteria helper and make the four methods async so a
thrown TypeORMError surfaces as a rejected promise, preserving the existing
contract.
…ehavior

- Strengthen the entity-instance passthrough test to assert DeleteResult.affected
  (1 for the populated instance, 0 for the null-column no-op) on drivers that
  report it, in addition to the existing row-existence checks.
- Document in null-and-undefined-handling: write methods reject criteria that is
  empty after normalization (guards against WHERE 1=1), and entity class
  instances are passed through unchanged (not validated by invalidWhereValuesBehavior).
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Deploying typeorm with  Cloudflare Pages  Cloudflare Pages

Latest commit: 073cb4b
Status: ✅  Deploy successful!
Preview URL: https://753adab9.typeorm.pages.dev
Branch Preview URL: https://fix-normalize-where-plain-ob.typeorm.pages.dev

View logs

naorpeled added 5 commits July 4, 2026 19:00
…ic arrays

The array branch recursively called isCriteriaNullOrEmpty on each element,
which stack-overflows (RangeError) on a self-referential array (const a=[];
a.push(a)) — reachable from EntityManager update/delete/softDelete/restore
criteria validation. Inspect array elements only one level deep with a
non-recursive emptiness check; this still catches every real empty shape
([], [{}], [null]) without recursing into nested/cyclic arrays.
…path

Per maintainer review: the read path (SelectQueryBuilder.buildWhere) validates
every key of the where criteria against invalidWhereValuesBehavior regardless of
whether it was given a plain object or a loaded entity instance. The write path
(update/delete/softDelete/restore) previously bypassed validation for entity
instances via a !isPlainObject early-return in normalizeWhereCriteria, so the
same input threw on find() but silently built `col = NULL` on delete().

Normalize entity instances the same as plain objects so both paths behave
identically. Primitives and atomic value-types (Date, Buffer/Uint8Array) are
still passed through untouched (delete-by-id and binary criteria unaffected),
and unconfigured data sources are unchanged (early return when no options).
Update tests and docs accordingly.
An array criteria element that is itself an empty array (e.g. [[]]) produces
zero predicates and renders as an always-true `1=1` OR-branch, turning
update/delete/softDelete/restore into unfiltered operations when
invalidWhereValuesBehavior is unset (normalizeWhereCriteria passes criteria
through untouched). Treat a zero-length array element as empty. This is a plain
length check, not a recursive call, so cyclic arrays remain safe from unbounded
recursion.
…elper doc

Address two review findings:
- Primitive id / id-array criteria (executed via whereInIds) was normalized and
  run through the OR-branch emptiness rules because validation ran before the
  isPrimitiveCriteria() branch. That could reject valid IN-lists (e.g. a string
  id list containing "") and needlessly mapped large id lists. Check
  isPrimitiveCriteria() first: primitive criteria is only rejected when wholly
  empty and returned untouched; object criteria is normalized and gets the
  per-element empty-OR-branch check. isCriteriaNullOrEmpty() reverts to a shallow
  whole-emptiness check (also removes any recursion concern).
- Correct the normalizeAndValidateWhereCriteria doc comment: it validates entity
  class instances too, not only plain objects.
manager.findBy/delete take the entity target as the first argument; the
example omitted it (manager.delete(post) -> manager.delete(Post, post)).
@github-actions github-actions Bot added the needs-triage PR needs issue link triage label Jul 4, 2026
naorpeled added 3 commits July 5, 2026 01:31
Move the authoritative description of invalidWhereValuesBehavior handling onto
OrmUtils.normalizeWhereCriteria, trim the EntityManager helper comment to defer
to it, and describe entity-instance validation in prose (removing the example
code block). No behavior change.
…rn honestly

The returned criteria is the raw id/id-array for the primitive (whereInIds)
branch, not necessarily an object; type it as any so callers aren't misled into
treating a primitive result as an object.
Guard update/delete/softDelete/restore at the point the WHERE is built: if a
WHERE was provided but renders empty ("1=1"), throw instead of emitting an
unfiltered statement. This closes the remaining full-table vector where criteria
look non-empty at the top level but expand to zero predicates — e.g. a relation
key whose value is a keyless object ({ category: new Category() }). Callers that
intend to affect all rows use updateAll()/deleteAll(), which set no WHERE.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

When invalidWhereValuesBehavior is unset, the write path (update/delete/
softDelete/restore) passed null/undefined through unchanged (col = NULL), while
the read/find path and the documented default treat a missing behavior as
"throw". Default the option to {} so per-key resolution yields "throw",
aligning writes with reads. Configured behaviors (ignore/sql-null) are
unaffected.
@naorpeled naorpeled changed the title fix(entity-manager): reject where criteria that collapse to WHERE 1=1 on update/delete fix(query-builder): reject empty where criteria on update and delete operations Jul 5, 2026
The default-throw alignment broke a legitimate operation — TreeRepository
softDelete with { parentId: null } on an unconfigured data source
(tree-tables/materialized-path/soft-delete-parent). Changing the unconfigured
write default from passthrough to throw is a breaking change to established
behavior that existing (including internal tree) code relies on; it needs a
deliberate, separately-tested change rather than being bundled here. Keeps the
QueryBuilder empty-WHERE guard, which is unaffected.

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

just some nits, lgtm!

Comment thread src/query-builder/QueryBuilder.ts Outdated
// the top level but expand to zero predicates (e.g. a relation key whose
// value is a keyless object). To affect all rows, use the dedicated
// updateAll()/deleteAll() methods, which set no WHERE.
const writeQueryTypes = ["update", "delete", "soft-delete", "restore"]

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.

nit: this feels a little odd here - given that this is just building, surprised we don't store this as metadata as part of the object to denote what type of query it is

if anything maybe we could store this static list somewhere else outside of this protected member?

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.

Done 🙏

Comment thread src/query-builder/QueryBuilder.ts Outdated
// updateAll()/deleteAll() methods, which set no WHERE.
const writeQueryTypes = ["update", "delete", "soft-delete", "restore"]
if (
writeQueryTypes.indexOf(this.expressionMap.queryType) !== -1 &&

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.

nit: could use .includes(), but I think this is consistent with other areas

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.

Done 🙏

Comment thread src/query-builder/QueryBuilder.ts Outdated
) {
throw new TypeORMError(
`Empty criteria(s) are not allowed for the ${this.expressionMap.queryType} operation. ` +
`To affect all rows, use the dedicated updateAll/deleteAll methods.`,

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.

minor nit: if soft-delete/restore, there is no equivalent to map to, so all actions are being told to go to updateAll/deleteAll.

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.

Done 🙏

Comment thread src/util/OrmUtils.ts Outdated

@alumni alumni Jul 6, 2026 •

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.

The type of criteria is no longer reflecting the real life type?

It should be any in real life, but it's incorrectly cast when we call this method.

Comment thread src/util/OrmUtils.ts Outdated
criteria === null ||
typeof criteria !== "object" ||
criteria instanceof Date ||
isUint8Array(criteria)

@alumni alumni Jul 6, 2026 •

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.

Any code that requires a comment this long is probably doing something it shouldn't.

What would happen for other data types - I'm thinking maybe FindOperator or something like that? Or anything else you have not yet thought about?

Right know, we're iterating thought the Object entries for everything else that doesn't match all these things. But who knows what other values we could get here - last time we forgot about Buffer and Array (and BTW, we are forgetting about arrays here again!)

That's why we should ALWAYS check if it's the kind of value we'd like to work with before working with it (and not what it's not). So if we want to iterate through the Object.entries(criteria) we should make sure if makes sense to do that, e.g. it's a plain object criteria, not some instance of a class (like an entity or a FindOperator or an array which can be a sparse vector containing nulls).

A little bit below there's an if (OrmUtils.isPlainObject(value)) - since now the logic from all those functions in EntityManager was moved to this method, maybe it makes sense to bring it up here as well?

- normalizeWhereCriteria: guard the key iteration with a positive
  isPlainObject(criteria) check instead of enumerating value types to exclude.
  Entity/class instances, FindOperators, arrays, Date, Buffer and primitives are
  passed through untouched (deep entity validation needs metadata — out of
  scope). Type criteria as any and drop the casts at the call sites.
- QueryBuilder empty-WHERE guard: hoist the write query-type list to a
  module-level const, use Array.includes, and reword the error since
  soft-delete/restore have no *All equivalent.
- Update tests and docs to reflect plain-object-only normalization.
@naorpeled

Copy link
Copy Markdown
Member Author

@naorpeled all review comments from @alumni and @smith-xyz are addressed in 387633283 and CI is fully green (46/0) 🟢

  • normalizeWhereCriteria now guards key-iteration with a positive isPlainObject(criteria) check (entity/class instances, FindOperators, arrays, Date, Buffer, primitives pass through untouched); criteria typed any, casts dropped.
  • QB empty-WHERE guard: hoisted WRITE_QUERY_TYPES const, uses .includes(), and the error no longer suggests updateAll/deleteAll for soft-delete/restore.

Ready for release whenever you are 🙏

@smith-xyz smith-xyz added linked-issue PR references an issue and removed needs-triage PR needs issue link triage labels Jul 8, 2026
@sonarqubecloud

sonarqubecloud Bot commented Jul 8, 2026

Copy link
Copy Markdown

@alumni
alumni merged commit 81b9466 into master Jul 8, 2026
49 checks passed
@alumni
alumni deleted the fix/normalize-where-plain-object-proto branch July 8, 2026 18:04
@github-actions github-actions Bot added this to the 1.0 milestone Jul 8, 2026
alumni added a commit that referenced this pull request Jul 8, 2026
…operations (#12629)

(cherry picked from commit 81b9466)

Co-authored-by: Lucian Mocanu <[email protected]>
alumni added a commit that referenced this pull request Jul 8, 2026
…operations (#12629)

(cherry picked from commit 81b9466)

Co-authored-by: Lucian Mocanu <[email protected]>
@samkessaram

Copy link
Copy Markdown
Contributor

Hey, initial issue submitter here 👋

Just wanted to say thanks to all that worked on this, it obviously ended up being a bigger task than I initially thought. Appreciate the efforts!

@naorpeled

naorpeled commented Jul 20, 2026 •

Copy link
Copy Markdown
Member Author

Hey, initial issue submitter here 👋

Just wanted to say thanks to all that worked on this, it obviously ended up being a bigger task than I initially thought. Appreciate the efforts!

Thank you for opening the issue ❤️
You dropped this 👑

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

Labels

Development

Successfully merging this pull request may close these issues.

6 participants