Skip to content

fix(persistence): preserve select-false columns in entity subscriber events - #12493

Closed
mbursali93 wants to merge 2 commits into
typeorm:masterfrom
mbursali93:fix/12473-select-false-columns-missing-in-after-update-event
Closed

mbursali93 wants to merge 2 commits into
typeorm:masterfrom
mbursali93:fix/12473-select-false-columns-missing-in-after-update-event

Conversation

@mbursali93

Copy link
Copy Markdown

Problem

select: false columns are missing from event.entity in entity subscriber events (afterInsert, afterUpdate) because SubjectExecutor mutates the entity object before broadcasting.

Root Cause

SubjectExecutor manipulates the entity during execution. By the time broadcastAfterEventsForAll is called, select: false columns have been stripped from the entity.

Fix

Added snapshotEntity() method to Subject class that takes a shallow copy of the entity before execution begins. Broadcaster uses originalEntity ?? entity to ensure original values are preserved.

Testing

Added integration tests for afterInsert and afterUpdate subscriber events verifying that select: false columns are present.

Fixes #12473

@mbursali93 mbursali93 changed the title fix(persistence): preserve select:false columns in entity subscriber … fix(persistence): preserve "select false" columns in entity subscriber events May 14, 2026
@mbursali93 mbursali93 changed the title fix(persistence): preserve "select false" columns in entity subscriber events fix(persistence): preserve select-false columns in entity subscriber events May 14, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 14, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (4)

Grey Divider


Action required

1. originalEntity! non-null assertion 📘 Rule violation ⛨ Security ⭐ New
Description
SubjectExecutor now passes subject.originalEntity! into after-insert/update broadcaster calls,
using a non-null assertion to bypass TypeScript’s null-safety. This can mask real undefined cases
at runtime and violates the requirement to avoid type-bypassing patterns.
Code

src/persistence/SubjectExecutor.ts[R299-305]

                this.queryRunner.broadcaster.broadcastAfterInsertEvent(
                    result,
                    subject.metadata,
-                    subject.entity!,
+                    subject.originalEntity!,
                    subject.identifier,
                ),
            )
Evidence
The checklist forbids type-bypassing patterns (e.g., casts used to silence type errors). The PR
introduces non-null assertions when passing subject.originalEntity to subscriber events, which is
a direct type-safety bypass.

Rule 4: Remove AI-generated noise
src/persistence/SubjectExecutor.ts[299-312]

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

## Issue description
`SubjectExecutor` uses `subject.originalEntity!`, which bypasses TypeScript null checks and can crash at runtime if `originalEntity` is not set.

## Issue Context
`originalEntity` is declared optional on `Subject`, so forcing it with `!` is a type-bypass pattern and can hide real edge-cases (e.g., subjects without entities).

## Fix Focus Areas
- src/persistence/SubjectExecutor.ts[299-312]

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


2. Snapshot breaks entity listeners 🐞 Bug ≡ Correctness ⭐ New
Description
Subject.snapshotEntity() clones entities via object spread, which drops the entity prototype and
changes constructor to Object. Since the broadcaster gates entity listeners by checking
entity.constructor/instanceof, afterInsert/afterUpdate entity listeners can stop firing and
subscribers will receive a non-entity instance in event.entity.
Code

src/persistence/Subject.ts[R348-351]

+    snapshotEntity(): void {
+        if (this.entity && !this.originalEntity) {
+            this.originalEntity = { ...this.entity }
+        }
Evidence
The snapshot is created with object spread (plain object), and after-insert/update broadcasts now
pass that snapshot into the broadcaster. Entity listeners are only executed when
listener.isAllowed(entity) is true, and isAllowed relies on the entity’s constructor/prototype
chain—this will fail for a plain object. The broadcaster also forwards the entity argument
directly into subscriber event payloads (entity: entity), so subscribers will observe the plain
object instance.

src/persistence/Subject.ts[344-352]
src/persistence/SubjectExecutor.ts[295-316]
src/metadata/EntityListenerMetadata.ts[61-74]
src/subscriber/Broadcaster.ts[417-452]
src/subscriber/Broadcaster.ts[687-723]

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

### Issue description
`Subject.snapshotEntity()` uses `{ ...this.entity }`, producing a plain object. That breaks entity listener matching (`EntityListenerMetadata.isAllowed`) and changes the runtime type of `event.entity` delivered to subscribers/listeners.

### Issue Context
After-events now pass `subject.originalEntity` into the broadcaster, so the snapshot’s runtime type matters for both entity listeners and subscriber code that expects an entity instance.

### Fix Focus Areas
- src/persistence/Subject.ts[344-352]
- src/persistence/SubjectExecutor.ts[295-316]

### Suggested fix
- Change the snapshot to preserve the original prototype, e.g.:
 - `this.originalEntity = Object.assign(Object.create(Object.getPrototypeOf(this.entity)), this.entity)`
- Consider passing `subject.originalEntity ?? subject.entity` to the broadcaster so behavior is safe even if a snapshot is absent.

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


3. Issue tests added in test/github-issues 📘 Rule violation ⚙ Maintainability
Description
This PR adds new tests under test/github-issues/12473, but the checklist requires issue fixes to
be covered by the functional test suite. Keeping issue-regression coverage outside test/functional
risks fragmented and harder-to-maintain test coverage.
Code

test/github-issues/12473/issue-12473.test.ts[R1-83]

+import { expect } from "chai"
+import type {
+    DataSource,
+    EntitySubscriberInterface,
+    InsertEvent,
+    UpdateEvent,
+} from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { MyEntity } from "./entity/MyEntity"
+
+describe("github issues > #12473 > select:false columns should be present in subscriber events", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [MyEntity],
+            schemaCreate: true,
+            dropSchema: true,
+            subscribers: [],
+        })
+    })
+
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should include select:false columns in afterInsert event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterInsert(event: InsertEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.save({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret")
+            }),
+        ))
+
+    it("should include select:false columns in afterUpdate event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterUpdate(event: UpdateEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.insert({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                await repo.save({
+                    id: 1,
+                    normalCol: "updated",
+                    selectFalseCol: "secret-updated",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret-updated")
+            }),
+        ))
+})
Evidence
Compliance ID 3 requires issue fixes to add/update tests under test/functional. The added
regression test file is located under test/github-issues/12473, which matches the failure criteria
of placing issue-only tests outside the functional suite without a clear reason.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/12473/issue-12473.test.ts[1-83]

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 regression tests were added under `test/github-issues`, but the project policy prefers placing issue fix coverage into `test/functional`.
## Issue Context
The PR introduces `test/github-issues/12473/issue-12473.test.ts` to cover issue #12473. The compliance checklist requires issue fixes to live in the functional suite (typically `test/functional`) unless there is a clearly stated exception.
## Fix Focus Areas
- test/github-issues/12473/issue-12473.test.ts[1-83]

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


View more (3)
4. Commented-out code in MyEntity.ts ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new test entity file includes commented-out imports and a fully commented subscriber scaffold,
plus placeholder comments. This adds noise inconsistent with clean test fixtures and violates the
rule against AI-like/placeholder comments and type-bypassing patterns.
Code

test/github-issues/12473/entity/MyEntity.ts[R1-36]

+import {
+    BaseEntity,
+    Column,
+    Entity,
+    // EntitySubscriberInterface,
+    // EventSubscriber,
+    PrimaryGeneratedColumn,
+    // UpdateEvent,
+} from "../../../../src"
+
+// entity
+@Entity()
+export class MyEntity extends BaseEntity {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    normalCol: string
+
+    @Column({ select: false })
+    selectFalseCol: string
+
+    // ...other columns
+}
+
+// subscriber to register
+// @EventSubscriber()
+// export class MyEntitySubscriber implements EntitySubscriberInterface<MyEntity> {
+//     listenTo() {
+//         return MyEntity
+//     }
+
+//     async afterUpdate(event: UpdateEvent<MyEntity>) {
+//         console.log(event.entity)
+//     }
+// }
Evidence
Compliance ID 4 forbids introducing AI-like noise such as extra comments and unnecessary
commented-out blocks. The added MyEntity.ts contains multiple commented-out imports and a full
commented subscriber implementation scaffold that is not used by the test.

Rule 4: Remove AI-generated noise
test/github-issues/12473/entity/MyEntity.ts[1-36]

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

## Issue description
A new test entity file contains commented-out imports and an entire commented subscriber example, which is unnecessary for the test and introduces noise.
## Issue Context
The compliance checklist requires avoiding AI-generated/placeholder comments and unnecessary commented code.
## Fix Focus Areas
- test/github-issues/12473/entity/MyEntity.ts[1-36]

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


5. structuredClone crashes on Promises ✓ Resolved 🐞 Bug ☼ Reliability
Description
Subject.snapshotEntity() uses structuredClone(this.entity), which will throw if the entity
contains non-cloneable values such as the lazy-relation Promise stored on the entity. This can crash
save/update execution before queries complete or events are broadcast.
Code

src/persistence/Subject.ts[R348-351]

+    snapshotEntity(): void {
+        if (this.entity && !this.originalEntity) {
+            this.originalEntity = structuredClone(this.entity)
+        }
Evidence
snapshotEntity() calls structuredClone() on every subject entity, while lazy relations
explicitly persist a Promise on the entity object, making it possible for the snapshot to encounter
a Promise-valued own property during save/update.

src/persistence/Subject.ts[344-352]
src/persistence/Subject.ts[147-179]
src/query-builder/RelationLoader.ts[461-481]

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

## Issue description
`Subject.snapshotEntity()` deep-clones the entity with `structuredClone()`. Entities can contain lazy-relation internal Promise properties (e.g. `__promise_<relation>__`), which makes `structuredClone()` throw at runtime, breaking persistence operations.
## Issue Context
TypeORM lazy-relations store the in-flight load promise on the entity as an own property (`entity[promiseIndex] = value`). Snapshotting is executed in the `Subject` constructor, so this failure happens early in the persistence pipeline.
## Fix Focus Areas
- src/persistence/Subject.ts[147-179]
- src/persistence/Subject.ts[344-352]
- src/query-builder/RelationLoader.ts[461-481]
## Suggested fix direction
- Do **not** `structuredClone()` the full entity.
- Instead, capture only what you need to preserve for after-events (e.g. values of `!column.isSelect` columns) into a safe structure (map of column paths -> value), or create a clone routine that:
- preserves prototype (e.g. `OrmUtils.cloneObject()`), and
- skips/retains-by-reference non-cloneable values (Promises) rather than throwing.
- Ensure snapshotting cannot throw for valid entity shapes (lazy relations, proxies).

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


6. After events use stale entity 🐞 Bug ≡ Correctness
Description
broadcastAfterEventsForAll() now passes subject.originalEntity (snapshotted in the Subject
constructor) into afterInsert/afterUpdate, so subscribers/listeners won’t see later mutations
applied to subject.entity (including changes from before* hooks and post-persist special-column
updates). This can make afterInsert/afterUpdate observe values that differ from what was actually
persisted and/or omit generated/special column updates that TypeORM explicitly applies before
after-events.
Code

src/persistence/SubjectExecutor.ts[R308-314]

              this.queryRunner.broadcaster.broadcastAfterUpdateEvent(
                  result,
                  subject.metadata,
-                    subject.entity!,
+                    subject.originalEntity!,
                  subject.databaseEntity,
                  subject.diffColumns,
                  subject.diffRelations,
Evidence
After-events are broadcast after updateSpecialColumnsInPersistedEntities() mutates
subject.entity (including deleting select:false fields), but the PR now passes a
constructor-time snapshot instead of the post-mutation entity; additionally, the executor explicitly
recomputes after before* events because those hooks can mutate entities, which the
constructor-time snapshot cannot reflect.

src/persistence/SubjectExecutor.ts[161-187]
src/persistence/SubjectExecutor.ts[295-316]
src/persistence/SubjectExecutor.ts[1020-1061]
src/persistence/Subject.ts[147-179]

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

## Issue description
`afterInsert/afterUpdate` events are now broadcast with `subject.originalEntity`, but that snapshot is taken in the `Subject` constructor (pre-`before*` hooks and pre-post-persist mutations). This causes after-events to receive an entity snapshot that can be stale and missing expected post-persist updates.
## Issue Context
Execution order:
1) `Subject` constructor snapshots immediately.
2) `SubjectExecutor.execute()` broadcasts `before*` events; it even recomputes subjects because `before*` handlers may mutate entities.
3) Persistence runs, then `updateSpecialColumnsInPersistedEntities()` mutates `subject.entity` (e.g., setting nullables, updating relation ids, and deleting `select:false` columns) before after-events.
4) After-events are broadcast.
Passing the constructor-time snapshot into after-events bypasses (2) and (3).
## Fix Focus Areas
- src/persistence/SubjectExecutor.ts[161-187]
- src/persistence/SubjectExecutor.ts[295-316]
- src/persistence/SubjectExecutor.ts[1020-1061]
- src/persistence/Subject.ts[147-179]
## Suggested fix direction
- Do not broadcast after-events with the constructor-time snapshot.
- Instead, preserve `select:false` values at the point they are about to be stripped (inside `updateSpecialColumnsInInsertedAndUpdatedEntities`), then construct an after-event entity that:
- starts from the final `subject.entity` (so it includes generated/special columns + any `before*` mutations), and
- restores only the `select:false` fields from the preserved values (including embedded paths).
- Update broadcaster calls to use `entityForAfterEvent` (or `subject.originalEntity ?? subject.entity` if you keep `originalEntity` as that after-event-specific copy).
- Ensure this works for embedded `select:false` columns (since deletion targets embedded objects via `OrmUtils.deepValue`).

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



Remediation recommended

7. capturedEntity typed as any 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The newly added tests declare capturedEntity: any and use a forced cast (`as
EntitySubscriberInterface<MyEntity>`), which are type-bypassing patterns. This increases maintenance
risk and violates the guideline to avoid any/casts used to silence typing issues.
Code

test/github-issues/12473/issue-12473.test.ts[R33-65]

+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterInsert(event: InsertEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.save({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret")
+            }),
+        ))
+
+    it("should include select:false columns in afterUpdate event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterUpdate(event: UpdateEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
Evidence
Rule 4 disallows type-bypassing patterns. The added test code introduces capturedEntity: any and
forces a subscriber object type with as EntitySubscriberInterface<MyEntity>, which are both used
to bypass compiler checks.

Rule 4: Remove AI-generated noise
test/github-issues/12473/issue-12473.test.ts[33-65]

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 test uses `any` and forced casting, bypassing TypeScript type-safety.

## Issue Context
Compliance requires avoiding type-bypassing patterns (like `any` and casts used to silence type errors), even in tests.

## Fix Focus Areas
- test/github-issues/12473/issue-12473.test.ts[33-65]

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


8. Subscriber change undocumented 📘 Rule violation ⚙ Maintainability ⭐ New
Description
This PR changes the value passed as event.entity in afterInsert/afterUpdate broadcasts (now
originalEntity), which is observable behavior for users of subscribers. No documentation updates
are included alongside this user-facing behavior change.
Code

src/persistence/SubjectExecutor.ts[R299-305]

                this.queryRunner.broadcaster.broadcastAfterInsertEvent(
                    result,
                    subject.metadata,
-                    subject.entity!,
+                    subject.originalEntity!,
                    subject.identifier,
                ),
            )
Evidence
Rule 2 requires updating documentation for user-facing changes. The diff shows a behavioral change
in what is broadcast to afterInsert/afterUpdate subscriber events (the event.entity argument),
which should be documented for users relying on subscriber semantics.

Rule 2: Docs updated for user-facing changes
src/persistence/SubjectExecutor.ts[299-314]

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

## Issue description
User-observable subscriber event behavior changed (what is passed as `event.entity`), but the PR does not include corresponding documentation updates.

## Issue Context
The compliance checklist requires docs/sample updates for user-facing changes.

## Fix Focus Areas
- src/persistence/SubjectExecutor.ts[299-314]

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


9. Tests leak subscribers 🐞 Bug ☼ Reliability ⭐ New
Description
The new tests push dynamic subscribers onto dataSource.subscribers but never remove them, so later
tests in the same suite can run with extra subscribers unexpectedly. This creates order-dependent
behavior and can make failures hard to diagnose.
Code

test/github-issues/12473/issue-12473.test.ts[R35-64]

+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterInsert(event: InsertEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.save({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret")
+            }),
+        ))
+
+    it("should include select:false columns in afterUpdate event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterUpdate(event: UpdateEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
Evidence
The issue test file pushes subscribers for both test cases but has no corresponding removal. A
comparable functional test demonstrates the expected pattern: push the subscriber, then remove it in
a finally block to prevent cross-test side effects.

test/github-issues/12473/issue-12473.test.ts[30-65]
test/github-issues/12473/issue-12473.test.ts[54-83]
test/functional/columns/value-transformer/value-transformer-change-detection.test.ts[40-60]

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 tests add subscribers via `dataSource.subscribers.push(...)` and don’t clean them up. Since the same `dataSources` are reused across test cases, subscribers accumulate.

### Issue Context
There is an established pattern in the test suite to remove dynamically-added subscribers in a `finally` block to avoid cross-test coupling.

### Fix Focus Areas
- test/github-issues/12473/issue-12473.test.ts[30-83]

### Suggested fix
- Store the subscriber in a variable, `push` it, and `splice` it out in a `finally` block (or add an `afterEach` cleanup) similar to other functional tests.

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


Grey Divider

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

Previous review results

Review updated until commit c429dcb

Results up to commit N/A


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


Action required
1. Issue tests added in test/github-issues 📘 Rule violation ⚙ Maintainability
Description
This PR adds new tests under test/github-issues/12473, but the checklist requires issue fixes to
be covered by the functional test suite. Keeping issue-regression coverage outside test/functional
risks fragmented and harder-to-maintain test coverage.
Code

test/github-issues/12473/issue-12473.test.ts[R1-83]

+import { expect } from "chai"
+import type {
+    DataSource,
+    EntitySubscriberInterface,
+    InsertEvent,
+    UpdateEvent,
+} from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { MyEntity } from "./entity/MyEntity"
+
+describe("github issues > #12473 > select:false columns should be present in subscriber events", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [MyEntity],
+            schemaCreate: true,
+            dropSchema: true,
+            subscribers: [],
+        })
+    })
+
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should include select:false columns in afterInsert event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterInsert(event: InsertEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.save({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret")
+            }),
+        ))
+
+    it("should include select:false columns in afterUpdate event entity", async () =>
+        await Promise.all(
+            dataSources.map(async (dataSource) => {
+                let capturedEntity: any = null
+
+                dataSource.subscribers.push({
+                    listenTo: () => MyEntity,
+                    afterUpdate(event: UpdateEvent<MyEntity>) {
+                        capturedEntity = event.entity
+                    },
+                } as EntitySubscriberInterface<MyEntity>)
+
+                const repo = dataSource.getRepository(MyEntity)
+                await repo.insert({
+                    id: 1,
+                    normalCol: "normal",
+                    selectFalseCol: "secret",
+                })
+
+                await repo.save({
+                    id: 1,
+                    normalCol: "updated",
+                    selectFalseCol: "secret-updated",
+                })
+
+                expect(capturedEntity.selectFalseCol).to.not.be.undefined
+                expect(capturedEntity.selectFalseCol).to.equal("secret-updated")
+            }),
+        ))
+})
Evidence
Compliance ID 3 requires issue fixes to add/update tests under test/functional. The added
regression test file is located under test/github-issues/12473, which matches the failure criteria
of placing issue-only tests outside the functional suite without a clear reason.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/12473/issue-12473.test.ts[1-83]

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 regression tests were added under `test/github-issues`, but the project policy prefers placing issue fix coverage into `test/functional`.
## Issue Context
The PR introduces `test/github-issues/12473/issue-12473.test.ts` to cover issue #12473. The compliance checklist requires issue fixes to live in the functional suite (typically `test/functional`) unless there is a clearly stated exception.
## Fix Focus Areas
- test/github-issues/12473/issue-12473.test.ts[1-83]

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


2. Commented-out code in MyEntity.ts ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new test entity file includes commented-out imports and a fully commented subscriber scaffold,
plus placeholder comments. This adds noise inconsistent with clean test fixtures and violates the
rule against AI-like/placeholder comments and type-bypassing patterns.
Code

test/github-issues/12473/entity/MyEntity.ts[R1-36]

+import {
+    BaseEntity,
+    Column,
+    Entity,
+    // EntitySubscriberInterface,
+    // EventSubscriber,
+    PrimaryGeneratedColumn,
+    // UpdateEvent,
+} from "../../../../src"
+
+// entity
+@Entity()
+export class MyEntity extends BaseEntity {
+    @PrimaryGeneratedColumn()
+    id: number
+
+    @Column()
+    normalCol: string
+
+    @Column({ select: false })
+    selectFalseCol: string
+
+    // ...other columns
+}
+
+// subscriber to register
+// @EventSubscriber()
+// export class MyEntitySubscriber implements EntitySubscriberInterface<MyEntity> {
+//     listenTo() {
+//         return MyEntity
+//     }
+
+//     async afterUpdate(event: UpdateEvent<MyEntity>) {
+//         console.log(event.entity)
+//     }
+// }
Evidence
Compliance ID 4 forbids introducing AI-like noise such as extra comments and unnecessary
commented-out blocks. The added MyEntity.ts contains multiple commented-out imports and a full
commented subscriber implementation scaffold that is not used by the test.

Rule 4: Remove AI-generated noise
test/github-issues/12473/entity/MyEntity.ts[1-36]

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

## Issue description
A new test entity file contains commented-out imports and an entire commented subscriber example, which is unnecessary for the test and introduces noise.
## Issue Context
The compliance checklist requires avoiding AI-generated/placeholder comments and unnecessary commented code.
## Fix Focus Areas
- test/github-issues/12473/entity/MyEntity.ts[1-36]

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


3. structuredClone crashes on Promises ✓ Resolved 🐞 Bug ☼ Reliability
Description
Subject.snapshotEntity() uses structuredClone(this.entity), which will throw if the entity
contains non-cloneable values such as the lazy-relation Promise stored on the entity. This can crash
save/update execution before queries complete or events are broadcast.
Code

src/persistence/Subject.ts[R348-351]

+    snapshotEntity(): void {
+        if (this.entity && !this.originalEntity) {
+            this.originalEntity = structuredClone(this.entity)
+        }
Evidence
snapshotEntity() calls structuredClone() on every subject entity, while lazy relations
explicitly persist a Promise on the entity object, making it possible for the snapshot to encounter
a Promise-valued own property during save/update.

src/persistence/Subject.ts[344-352]
src/persistence/Subject.ts[147-179]
src/query-builder/RelationLoader.ts[461-481]

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

## Issue description
`Subject.snapshotEntity()` deep-clones the entity with `structuredClone()`. Entities can contain lazy-relation internal Promise properties (e.g. `__promise_<relation>__`), which makes `structuredClone()` throw at runtime, breaking persistence operations.
## Issue Context
TypeORM lazy-relations store the in-flight load promise on the entity as an own property (`entity[promiseIndex] = value`). Snapshotting is executed in the `Subject` constructor, so this failure happens early in the persistence pipeline.
## Fix Focus Areas
- src/persistence/Subject.ts[147-179]
- src/persistence/Subject.ts[344-352]
- src/query-builder/RelationLoader.ts[461-481]
## Suggested fix direction
- Do **not** `structuredClone()` the full entity.
- Instead, capture only what you need to preserve for after-events (e.g. values of `!column.isSelect` columns) into a safe structure (map of column paths -> value), or create a clone routine that:
- preserves prototype (e.g. `OrmUtils.cloneObject()`), and
- skips/retains-by-reference non-cloneable values (Promises) rather than throwing.
- Ensure snapshotting cannot throw for valid entity shapes (lazy relations, proxies).

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


View more (1)
4. After events use stale entity 🐞 Bug ≡ Correctness
Description
broadcastAfterEventsForAll() now passes subject.originalEntity (snapshotted in the Subject
constructor) into afterInsert/afterUpdate, so subscribers/listeners won’t see later mutations
applied to subject.entity (including changes from before* hooks and post-persist special-column
updates). This can make afterInsert/afterUpdate observe values that differ from what was actually
persisted and/or omit generated/special column updates that TypeORM explicitly applies before
after-events.
Code

src/persistence/SubjectExecutor.ts[R308-314]

               this.queryRunner.broadcaster.broadcastAfterUpdateEvent(
                   result,
                   subject.metadata,
-                    subject.entity!,
+                    subject.originalEntity!,
                   subject.databaseEntity,
                   subject.diffColumns,
                   subject.diffRelations,
Evidence
After-events are broadcast after updateSpecialColumnsInPersistedEntities() mutates
subject.entity (including deleting select:false fields), but the PR now passes a
constructor-time snapshot instead of the post-mutation entity; additionally, the executor explicitly
recomputes after before* events because those hooks can mutate entities, which the
constructor-time snapshot cannot reflect.

src/persistence/SubjectExecutor.ts[161-187]
src/persistence/SubjectExecutor.ts[295-316]
src/persistence/SubjectExecutor.ts[1020-1061]
src/persistence/Subject.ts[147-179]

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

## Issue description
`afterInsert/afterUpdate` events are now broadcast with `subject.originalEntity`, but that snapshot is taken in the `Subject` constructor (pre-`before*` hooks and pre-post-persist mutations). This causes after-events to receive an entity snapshot that can be stale and missing expected post-persist updates.
## Issue Context
Execution order:
1) `Subject` constructor snapshots immediately.
2) `SubjectExecutor.execute()` broadcasts `before*` events; it even recomputes subjects because `before*` handlers may mutate entities.
3) Persistence runs, then `updateSpecialColumnsInPersistedEntities()` mutates `subject.entity` (e.g., setting nullables, updating relation ids, and deleting `select:false` columns) before after-events.
4) After-events are broadcast.
Passing the constructor-time snapshot into after-events bypasses (2) and (3).
## Fix Focus Areas
- src/persistence/SubjectExecutor.ts[161-187]
- src/persistence/SubjectExecutor.ts[295-316]
- src/persistence/SubjectExecutor.ts[1020-1061]
- src/persistence/Subject.ts[147-179]
## Suggested fix direction
- Do not broadcast after-events with the constructor-time snapshot.
- Instead, preserve `select:false` values at the point they are about to be stripped (inside `updateSpecialColumnsInInsertedAndUpdatedEntities`), then construct an after-event entity that:
- starts from the final `subject.entity` (so it includes generated/special columns + any `before*` mutations), and
- restores only the `select:false` fields from the preserved values (including embedded paths).
- Update broadcaster calls to use `entityForAfterEvent` (or `subject.originalEntity ?? subject.entity` if you keep `originalEntity` as that after-event-specific copy).
- Ensure this works for embedded `select:false` columns (since deletion targets embedded objects via `OrmUtils.deepValue`).

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


Qodo Logo

@pkg-pr-new

pkg-pr-new Bot commented May 14, 2026

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

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

commit: c429dcb

@gioboa gioboa left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your help @mbursali93
Is this fix working for you @tada5hi @Johoseph ?

@tada5hi

tada5hi commented May 14, 2026

Copy link
Copy Markdown
Contributor

This PR routes only the subscriber broadcast (broadcastAfterInsertEvent, broadcastAfterUpdateEvent) through subject.originalEntity. The underlying delete target[column.propertyName] in SubjectExecutor.updateSpecialColumnsInInsertedAndUpdatedEntities (from #11944) still mutates subject.entity itself, which is the same reference repository.save() hands back to the caller — and the same reference the caller passed in. So select: false columns are still stripped from the post-save return value, just not from the subscriber event anymore.

Minimal repro (no subscriber):

@Entity()
class User {
    @PrimaryGeneratedColumn('uuid') id: string;
    @Column() name: string;
    @Column({ select: false }) email: string;
}

const entity = repo.create({ name: 'foo', email: '[email protected]' });
const saved = await repo.save(entity);

console.log(saved.email);       // undefined on 0.3.29, '[email protected]' on 0.3.28
console.log('email' in entity); // false on 0.3.29, true on 0.3.28 (passed-in ref is mutated too)

To fully restore the 0.3.28 contract, the snapshot-and-restore needs to apply to subject.entity as well — either by restoring stripped properties onto subject.entity after updateSpecialColumnsInInsertedAndUpdatedEntities runs, or by avoiding the delete altogether and computing the "DB-shaped" projection only at the broadcast boundary. The current diff leaves the second symptom in place; further context in #12473.

@alumni

alumni commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Hi @mbursali93 thanks for the contribution!

We decided instead to revert the PR that introduced the bug, by merging #12501. I think it's the right thing to do considering the original issue - see #4591 (comment)

@alumni alumni closed this Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

select: false columns are no longer available in event subscriber afterUpdate

4 participants