Skip to content

fix: fix up save with eagerly loaded relation - #11975

Merged
gioboa merged 2 commits into
typeorm:masterfrom
gioboa:fix/11905
Feb 14, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
gioboa:fix/11905

Conversation

@gioboa

@gioboa gioboa commented Feb 10, 2026

Copy link
Copy Markdown
Collaborator

Close #11905

Description of change

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

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

Copy link
Copy Markdown

User description

Close #11905

Description of change

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

PR Type

Bug fix


Description

  • Skip persistence-disabled relations in changed columns computation

  • Prevent errors when saving entities with eagerly loaded non-persistent relations

  • Add JSDoc parameters to document method arguments

  • Add test cases for eager loading with non-persistent relations


Diagram Walkthrough

flowchart LR
  A["Entity with<br/>non-persistent relations"] -->|"save()"| B["SubjectChangedColumnsComputer"]
  B -->|"check persistence flag"| C["Skip disabled relations"]
  C -->|"compute only<br/>persistent columns"| D["Successful save"]
Loading

File Walkthrough

Relevant files
Bug fix
SubjectChangedColumnsComputer.ts
Skip non-persistent relations in change detection               

src/persistence/SubjectChangedColumnsComputer.ts

  • Added check to skip relations with persistenceEnabled === false in
    computeDiffRelationalColumns method
  • Added JSDoc parameter documentation for compute, computeDiffColumns,
    and computeDiffRelationalColumns methods
  • Prevents processing of non-persistent relations during change
    detection
+6/-0     
Tests
MainEntity.ts
Test entity with non-persistent relations                               

test/functional/find-options/select/entity/MainEntity.ts

  • New test entity with multiple one-to-one relations sharing same column
  • Demonstrates issue with non-persistent relations marked with
    persistence: false
  • Includes updateRelatedStatus() method that triggers the save operation
+59/-0   
OptionA.ts
Test entity for relation option A                                               

test/functional/find-options/select/entity/OptionA.ts

  • New test entity representing one-to-one relation target
  • Lazy-loaded relation back to MainEntity
+16/-0   
OptionB.ts
Test entity for relation option B                                               

test/functional/find-options/select/entity/OptionB.ts

  • New test entity representing one-to-one relation target
  • Lazy-loaded relation back to MainEntity
+16/-0   
RelatedEntity.ts
Test entity for many-to-one relation                                         

test/functional/find-options/select/entity/RelatedEntity.ts

  • New test entity with one-to-many relation to MainEntity
  • Includes status column for testing relation updates
+20/-0   
find-options-select.test.ts
Add tests for non-persistent relation handling                     

test/functional/find-options/select/find-options-select.test.ts

  • Added imports for new test entities and chai expect
  • Added test case for non-eagerly loaded relations
  • Added test case for eagerly loaded relations with non-persistent
    relation handling
  • Both tests verify successful save and reload operations
+43/-0   

@pkg-pr-new

pkg-pr-new Bot commented Feb 10, 2026 •

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

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

commit: bc3feac

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to bc3feac

CategorySuggestion                                                                                                                                    Impact
Possible issue
Skip unresolved lazy relation values

Add a check in computeDiffRelationalColumns to skip diffing for unresolved lazy
relations (Promises/thenables) to prevent incorrect change detection.

src/persistence/SubjectChangedColumnsComputer.ts [225-231]

 subject.metadata.relationsWithJoinColumns.forEach((relation) => {
     if (relation.persistenceEnabled === false) return
 
     // get the related entity from the persisted entity
     let relatedEntity = relation.getEntityValue(subject.entity!)
 
+    // if relation is lazy and not resolved (Promise/thenable), don't treat it as a changed value
+    if (
+        relatedEntity &&
+        typeof (relatedEntity as any).then === "function"
+    ) {
+        return
+    }
+
     // we don't perform operation over undefined properties (but we DO need null properties!)
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug where an unresolved lazy relation (a Promise) could be incorrectly processed, leading to unwanted database updates, and proposes a valid fix.

High
General
Make updates transactional

Wrap the two save calls within updateRelatedStatus in a transaction to ensure
the update sequence is atomic.

test/functional/find-options/select-lazy/entity/MainEntity.ts [54-59]

 async updateRelatedStatus(manager: EntityManager) {
-    const related = await this.related
-    related.status = true
-    await manager.save(this)
-    await manager.save(related)
+    await manager.transaction(async (tx) => {
+        const related = await this.related
+        related.status = true
+        await tx.save(this)
+        await tx.save(related)
+    })
 }
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly points out that wrapping multiple save calls in a transaction improves atomicity, which is a good practice, but it's an improvement to a test helper function, not production code.

Low
  • More

Previous suggestions

Suggestions up to commit babc9c0
CategorySuggestion                                                                                                                                    Impact
Possible issue
Skip diffing unresolved lazy relations

In computeDiffRelationalColumns, add a check to determine if relatedEntity is a
Promise. If it is, skip the diffing logic for that relation to avoid errors with
unresolved lazy relations.

src/persistence/SubjectChangedColumnsComputer.ts [225-231]

 subject.metadata.relationsWithJoinColumns.forEach((relation) => {
     if (relation.persistenceEnabled === false) return
 
     // get the related entity from the persisted entity
     let relatedEntity = relation.getEntityValue(subject.entity!)
 
+    // if relation is lazy and still unresolved, skip diffing it
+    if (ObjectUtils.isPromise(relatedEntity)) return
+
     // we don't perform operation over undefined properties (but we DO need null properties!)
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential bug where an unresolved lazy relation promise could be treated as an entity object, leading to incorrect behavior during persistence. Adding this check improves the robustness and correctness of handling lazy relations.

Medium
Suggestions up to commit 3328582
CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid triggering lazy relation getters

To avoid accidentally triggering lazy relation getters, add a check to ensure
the relation property is not defined via a getter before accessing its value.

src/persistence/SubjectChangedColumnsComputer.ts [66-75]

 // filter out "relational columns" only in the case if there is a relation object in entity
 if (
     column.relationMetadata &&
-    column.relationMetadata.persistenceEnabled !== false
+    column.relationMetadata.persistenceEnabled !== false &&
+    !Object.getOwnPropertyDescriptor(
+        subject.entity!,
+        column.relationMetadata.propertyName,
+    )?.get
 ) {
-    const value = column.relationMetadata.getEntityValue(
-        subject.entity!,
-    )
+    const value = column.relationMetadata.getEntityValue(subject.entity!)
     if (value !== null && value !== undefined) return
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug in the new code where calling getEntityValue on a lazy relation would trigger it, causing incorrect behavior and performance issues. The proposed fix is correct and consistent with patterns elsewhere in the codebase.

High
Suggestions up to commit d984914
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent unintended lazy relation loads

In SubjectChangedColumnsComputer.ts, add a check to prevent invoking
lazy-relation getters, which can trigger unintended database queries when
determining changed columns.

src/persistence/SubjectChangedColumnsComputer.ts [66-75]

 // filter out "relational columns" only in the case if there is a relation object in entity
 if (
     column.relationMetadata &&
-    column.relationMetadata.persistenceEnabled !== false
+    column.relationMetadata.persistenceEnabled !== false &&
+    !Object.getOwnPropertyDescriptor(
+        subject.entity!,
+        column.relationMetadata.propertyName,
+    )?.get
 ) {
-    const value = column.relationMetadata.getEntityValue(
-        subject.entity!,
-    )
+    const value = column.relationMetadata.getEntityValue(subject.entity!)
     if (value !== null && value !== undefined) return
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential for unintended database queries by invoking lazy-relation getters and proposes a fix that aligns with a pattern already used elsewhere in the PR.

Medium
Suggestions up to commit ea1055d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Don’t skip diffs for lazy placeholders

In SubjectChangedColumnsComputer.ts, avoid incorrectly skipping foreign key
column diffs for uninitialized lazy relations by checking for property getters
before accessing the relation value, thus preventing accidental database
queries.

src/persistence/SubjectChangedColumnsComputer.ts [68-75]

 // filter out "relational columns" only in the case if there is a relation object in entity
 if (
     column.relationMetadata &&
     column.relationMetadata.persistenceEnabled !== false
 ) {
-    const value = column.relationMetadata.getEntityValue(
+    const descriptor = Object.getOwnPropertyDescriptor(
         subject.entity!,
+        column.relationMetadata.propertyName,
     )
-    if (value !== null && value !== undefined) return
+
+    // don't invoke lazy getter / trigger query
+    if (!descriptor?.get) {
+        const value = column.relationMetadata.getEntityValue(subject.entity!)
+
+        // skip only when an actual related entity is present (not a Promise/thenable placeholder)
+        const isThenable =
+            value !== null &&
+            value !== undefined &&
+            typeof (value as any)?.then === "function"
+
+        if (value !== null && value !== undefined && !isThenable) return
+    }
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the current code might trigger an unwanted lazy-load and incorrectly skip foreign key updates, and proposes a fix that is consistent with patterns used elsewhere in the codebase.

Medium
General
Clarify persistence gating logic

In ColumnMetadata.ts, clarify the logic for handling persistence by explicitly
checking if relationMetadata exists before checking its persistenceEnabled
property, improving readability and preventing edge-case bugs.

src/metadata/ColumnMetadata.ts [847-902]

 } else if (
     this.referencedColumn &&
-    this.relationMetadata?.persistenceEnabled !== false
+    (!this.relationMetadata ||
+        this.relationMetadata.persistenceEnabled !== false)
 ) {
     value = this.referencedColumn.getEntityValue(
         embeddedObject[this.propertyName],
     )
 } else if (isEmbeddedArray && Array.isArray(embeddedObject)) {
     value = embeddedObject.map((o) => o[this.propertyName])
 } else {
     value = embeddedObject[this.propertyName]
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion improves code clarity and robustness by making the condition for checking persistence more explicit, which prevents potential misinterpretation of the logic, especially when relationMetadata is undefined.

Low
Suggestions up to commit ec10c76
CategorySuggestion                                                                                                                                    Impact
Possible issue
Skip unresolved lazy relation values

Add a check to skip diffing for unresolved lazy relations (which are Promise
objects) to prevent incorrect change detection and potential errors.

src/persistence/SubjectChangedColumnsComputer.ts [225-231]

 subject.metadata.relationsWithJoinColumns.forEach((relation) => {
     if (relation.persistenceEnabled === false) return
 
     // get the related entity from the persisted entity
     let relatedEntity = relation.getEntityValue(subject.entity!)
 
+    // ignore unresolved lazy relations (Promise) unless explicitly set in the entity
+    if (ObjectUtils.isPromise(relatedEntity)) return
+
     // we don't perform operation over undefined properties (but we DO need null properties!)
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that an unresolved lazy relation (a Promise) can be mishandled during change detection. Adding a check to skip these promises improves the robustness of the persistence logic and prevents potential runtime errors, which is a valuable improvement.

Medium

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (9) 📘 Rule violations (8) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Cascade ignores persistence flag 🐞 Bug ✓ Correctness ⭐ New
Description
With the new persistenceEnabled guard, join columns won’t be updated from relations marked
persistence:false, but cascade insert/update can still run for those relations. This can persist the
related entity while leaving the owning FK unchanged, resulting in surprising partial persistence
(relationship not written).
Code

src/persistence/SubjectChangedColumnsComputer.ts[R225-228]

        subject.metadata.relationsWithJoinColumns.forEach((relation) => {
+            if (relation.persistenceEnabled === false) return
+
            // get the related entity from the persisted entity
Evidence
The PR adds an early-return for persistence-disabled relations in join-column diffing, meaning the
owning-side FK update won’t be produced from relation values. However, cascades are still built from
all relations without checking persistenceEnabled, unlike other relation persistence builders which
already skip persistence-disabled relations—creating an inconsistent pipeline where cascades can
execute without the corresponding relation/FK write.

src/persistence/SubjectChangedColumnsComputer.ts[225-228]
src/metadata/RelationMetadata.ts[107-113]
src/persistence/subject-builder/CascadesSubjectBuilder.ts[27-46]
src/persistence/subject-builder/OneToManySubjectBuilder.ts[34-38]
src/persistence/subject-builder/ManyToManySubjectBuilder.ts[33-39]

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

### Issue description
`computeDiffRelationalColumns` now skips join-column diffing for relations with `persistenceEnabled === false`. However, `CascadesSubjectBuilder` can still cascade insert/update/soft-remove/recover through those relations, potentially persisting related entities without updating the owning-side FK/join columns, leading to partial/inconsistent persistence.

### Issue Context
Other persistence builders (e.g., many-to-many/one-to-many) already respect `persistenceEnabled` by skipping such relations. Cascades should be consistent with this contract.

### Fix Focus Areas
- src/persistence/subject-builder/CascadesSubjectBuilder.ts[23-46]
- (reference) src/persistence/SubjectChangedColumnsComputer.ts[225-233]

### Suggested change
Add a guard inside the cascades loop:
- If `relation.persistenceEnabled === false`, skip building cascade subjects for that relation.

### Notes
Consider whether the guard should apply to all operation types handled in `CascadesSubjectBuilder` (save/soft-remove/recover), since those are the cascade types supported there.

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


2. Insert ignores persistence:false 🐞 Bug ✓ Correctness
Description
computeDiffRelationalColumns now skips persistence-disabled relations on update, but inserts can
still persist the join column when it reuses an explicit non-virtual @Column whose value is
derived from the relation object. This makes persistence: false behavior inconsistent between
insert vs update and can persist data users expected to remain read-only.
Code

src/persistence/SubjectChangedColumnsComputer.ts[R225-227]

      subject.metadata.relationsWithJoinColumns.forEach((relation) => {
+            if (relation.persistenceEnabled === false) return
+
Evidence
The PR change skips persistence-disabled relations during relational diffing. However, when a join
column reuses an existing explicit column, TypeORM attaches relationMetadata to that column;
ColumnMetadata.getEntityValue can then derive the column value from the relation object.
computeDiffColumns will still create a column changeMap for such non-virtual columns during
inserts because its “relational column” short-circuit only runs when subject.databaseEntity exists
(update path). Result: inserts may still write the FK derived from the relation object even when
persistenceEnabled is false, while updates won’t (due to the new guard).

src/persistence/SubjectChangedColumnsComputer.ts[218-233]
src/persistence/SubjectChangedColumnsComputer.ts[35-85]
src/persistence/SubjectChangedColumnsComputer.ts[203-209]
src/metadata-builder/RelationJoinColumnBuilder.ts[186-246]
src/metadata/ColumnMetadata.ts[847-873]
src/metadata/RelationMetadata.ts[108-113]

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

## Issue description
`computeDiffRelationalColumns` now skips `persistenceEnabled === false` relations, so UPDATE operations won’t create relation changeMaps. But when a join column reuses an explicit non-virtual `@Column`, `ColumnMetadata.getEntityValue` can still derive the FK value from the relation object, and `computeDiffColumns` will create a column changeMap during INSERTs (because the relational-column skip only runs when `subject.databaseEntity` exists). This can cause INSERTs to persist `persistence: false` relations while UPDATEs do not.
### Issue Context
We want `persistence: false` to reliably prevent relation-driven FK persistence.
### Fix Focus Areas
- src/persistence/SubjectChangedColumnsComputer.ts[35-85]
- src/persistence/SubjectChangedColumnsComputer.ts[203-209]
- src/persistence/SubjectChangedColumnsComputer.ts[218-233]
- src/metadata/ColumnMetadata.ts[847-873]
### Suggested approach
- In `computeDiffColumns`, when `column.relationMetadata?.persistenceEnabled === false`, do **not** create a column changeMap based on a non-null/non-undefined relation object (consider applying the existing relational-column short-circuit even when `subject.databaseEntity` is not set).
- Alternatively (or additionally), in `ColumnMetadata.getEntityValue`, if `this.relationMetadata?.persistenceEnabled === false`, avoid deriving the FK value from the relation object and prefer the scalar property value.
- Add/extend a functional test that inserts an entity with an explicit FK column reused by a `persistence:false` relation and sets only the relation object; assert the FK column is not persisted.

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


3. Insert ignores persistence:false 🐞 Bug ✓ Correctness
Description
computeDiffRelationalColumns now skips persistence-disabled relations on update, but inserts can
still persist the join column when it reuses an explicit non-virtual @Column whose value is
derived from the relation object. This makes persistence: false behavior inconsistent between
insert vs update and can persist data users expected to remain read-only.
Code

src/persistence/SubjectChangedColumnsComputer.ts[R225-227]

       subject.metadata.relationsWithJoinColumns.forEach((relation) => {
+            if (relation.persistenceEnabled === false) return
+
Evidence
The PR change skips persistence-disabled relations during relational diffing. However, when a join
column reuses an existing explicit column, TypeORM attaches relationMetadata to that column;
ColumnMetadata.getEntityValue can then derive the column value from the relation object.
computeDiffColumns will still create a column changeMap for such non-virtual columns during
inserts because its “relational column” short-circuit only runs when subject.databaseEntity exists
(update path). Result: inserts may still write the FK derived from the relation object even when
persistenceEnabled is false, while updates won’t (due to the new guard).

src/persistence/SubjectChangedColumnsComputer.ts[218-233]
src/persistence/SubjectChangedColumnsComputer.ts[35-85]
src/persistence/SubjectChangedColumnsComputer.ts[203-209]
src/metadata-builder/RelationJoinColumnBuilder.ts[186-246]
src/metadata/ColumnMetadata.ts[847-873]
src/metadata/RelationMetadata.ts[108-113]

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

## Issue description
`computeDiffRelationalColumns` now skips `persistenceEnabled === false` relations, so UPDATE operations won’t create relation changeMaps. But when a join column reuses an explicit non-virtual `@Column`, `ColumnMetadata.getEntityValue` can still derive the FK value from the relation object, and `computeDiffColumns` will create a column changeMap during INSERTs (because the relational-column skip only runs when `subject.databaseEntity` exists). This can cause INSERTs to persist `persistence: false` relations while UPDATEs do not.
### Issue Context
We want `persistence: false` to reliably prevent relation-driven FK persistence.
### Fix Focus Areas
- src/persistence/SubjectChangedColumnsComputer.ts[35-85]
- src/persistence/SubjectChangedColumnsComputer.ts[203-209]
- src/persistence/SubjectChangedColumnsComputer.ts[218-233]
- src/metadata/ColumnMetadata.ts[847-873]
### Suggested approach
- In `computeDiffColumns`, when `column.relationMetadata?.persistenceEnabled === false`, do **not** create a column changeMap based on a non-null/non-undefined relation object (consider applying the existing relational-column short-circuit even when `subject.databaseEntity` is not set).
- Alternatively (or additionally), in `ColumnMetadata.getEntityValue`, if `this.relationMetadata?.persistenceEnabled === false`, avoid deriving the FK value from the relation object and prefer the scalar property value.
- Add/extend a functional test that inserts an entity with an explicit FK column reused by a `persistence:false` relation and sets only the relation object; assert the FK column is not persisted.

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


View more (4)
4. ActiveRecord DS mismatch 🐞 Bug ⛯ Reliability
Description
New functional tests introduce BaseEntity entities and call .save()/.reload() while the suite
runs across multiple DataSources (often in parallel). BaseEntity uses a static DataSource set
during DataSource.initialize(), so with multiple initialized DataSources this can execute against
the wrong connection, causing flaky or incorrect test behavior.
Code

test/functional/find-options/select/entity/MainEntity.ts[R54-58]

+    async updateRelatedStatus() {
+        ;(await this.related).status = true
+        await this.save() // This is where the error occurs
+        await (await this.related).save()
+    }
Evidence
MainEntity.updateRelatedStatus() uses ActiveRecord .save() on entities extending BaseEntity.
BaseEntity.save() resolves its repository via a static dataSource field, which each
DataSource.initialize() overwrites for every BaseEntity subclass. createTestingConnections()
initializes multiple DataSources in a loop, and this suite executes test logic for all DataSources
via Promise.all, so ActiveRecord calls can be routed to whichever DataSource initialized last (or
be stomped during parallel execution).

test/functional/find-options/select/entity/MainEntity.ts[54-58]
src/repository/BaseEntity.ts[29-33]
src/repository/BaseEntity.ts[51-54]
src/repository/BaseEntity.ts[112-119]
src/data-source/DataSource.ts[779-786]
test/utils/test-utils.ts[388-397]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 functional test entities extend `BaseEntity` and use `.save()` / `.reload()` inside a suite that creates multiple `DataSource`s and runs per-`DataSource` tests via `Promise.all`. Because `BaseEntity` stores a static `DataSource` per entity class, those ActiveRecord calls can be executed against the wrong `DataSource` (typically whichever initialized last), making the tests flaky or incorrect.
### Issue Context
- ActiveRecord methods on `BaseEntity` resolve repositories from a static `dataSource`.
- Each `DataSource.initialize()` overwrites that static for all `BaseEntity` subclasses.
- The test suite runs the same assertions across multiple initialized `DataSource`s.
### Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[1-59]
- test/functional/find-options/select/entity/RelatedEntity.ts[1-20]
- test/functional/find-options/select/entity/OptionA.ts[1-16]
- test/functional/find-options/select/entity/OptionB.ts[1-16]
- test/functional/find-options/select/find-options-select.test.ts[191-229]
### Suggested approach
1. Remove `extends BaseEntity` (and `BaseEntity` imports) from the new test entities.
2. Update `MainEntity.updateRelatedStatus` to accept an `EntityManager` (or `DataSource`) and use `manager.save(...)` instead of `this.save()` / `(await this.related).save()`.
 - e.g. `async updateRelatedStatus(manager: EntityManager) { const related = await this.related; related.status = true; await manager.save(this); await manager.save(related); }`
3. Replace `.reload()` calls in the tests with `dataSource.manager.findOneByOrFail(...)` (or `findOne(...)` + assert) to re-fetch state from the correct `DataSource`.
4. Keep the test semantics (eager vs non-eager load) the same, but ensure *all* persistence operations go through the per-iteration `dataSource.manager`/repositories.

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


5. ActiveRecord DS mismatch 🐞 Bug ⛯ Reliability
Description
New functional tests introduce BaseEntity entities and call .save()/.reload() while the suite
runs across multiple DataSources (often in parallel). BaseEntity uses a static DataSource set
during DataSource.initialize(), so with multiple initialized DataSources this can execute against
the wrong connection, causing flaky or incorrect test behavior.
Code

test/functional/find-options/select/entity/MainEntity.ts[R54-58]

+    async updateRelatedStatus() {
+        ;(await this.related).status = true
+        await this.save() // This is where the error occurs
+        await (await this.related).save()
+    }
Evidence
MainEntity.updateRelatedStatus() uses ActiveRecord .save() on entities extending BaseEntity.
BaseEntity.save() resolves its repository via a static dataSource field, which each
DataSource.initialize() overwrites for every BaseEntity subclass. createTestingConnections()
initializes multiple DataSources in a loop, and this suite executes test logic for all DataSources
via Promise.all, so ActiveRecord calls can be routed to whichever DataSource initialized last (or
be stomped during parallel execution).

test/functional/find-options/select/entity/MainEntity.ts[54-58]
src/repository/BaseEntity.ts[29-33]
src/repository/BaseEntity.ts[51-54]
src/repository/BaseEntity.ts[112-119]
src/data-source/DataSource.ts[779-786]
test/utils/test-utils.ts[388-397]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 functional test entities extend `BaseEntity` and use `.save()` / `.reload()` inside a suite that creates multiple `DataSource`s and runs per-`DataSource` tests via `Promise.all`. Because `BaseEntity` stores a static `DataSource` per entity class, those ActiveRecord calls can be executed against the wrong `DataSource` (typically whichever initialized last), making the tests flaky or incorrect.
### Issue Context
- ActiveRecord methods on `BaseEntity` resolve repositories from a static `dataSource`.
- Each `DataSource.initialize()` overwrites that static for all `BaseEntity` subclasses.
- The test suite runs the same assertions across multiple initialized `DataSource`s.
### Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[1-59]
- test/functional/find-options/select/entity/RelatedEntity.ts[1-20]
- test/functional/find-options/select/entity/OptionA.ts[1-16]
- test/functional/find-options/select/entity/OptionB.ts[1-16]
- test/functional/find-options/select/find-options-select.test.ts[191-229]
### Suggested approach
1. Remove `extends BaseEntity` (and `BaseEntity` imports) from the new test entities.
2. Update `MainEntity.updateRelatedStatus` to accept an `EntityManager` (or `DataSource`) and use `manager.save(...)` instead of `this.save()` / `(await this.related).save()`.
- e.g. `async updateRelatedStatus(manager: EntityManager) { const related = await this.related; related.status = true; await manager.save(this); await manager.save(related); }`
3. Replace `.reload()` calls in the tests with `dataSource.manager.findOneByOrFail(...)` (or `findOne(...)` + assert) to re-fetch state from the correct `DataSource`.
4. Keep the test semantics (eager vs non-eager load) the same, but ensure *all* persistence operations go through the per-iteration `dataSource.manager`/repositories.

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


6. ActiveRecord DS mismatch 🐞 Bug ⛯ Reliability
Description
New functional tests introduce BaseEntity entities and call .save()/.reload() while the suite
runs across multiple DataSources (often in parallel). BaseEntity uses a static DataSource set
during DataSource.initialize(), so with multiple initialized DataSources this can execute against
the wrong connection, causing flaky or incorrect test behavior.
Code

test/functional/find-options/select/entity/MainEntity.ts[R54-58]

+    async updateRelatedStatus() {
+        ;(await this.related).status = true
+        await this.save() // This is where the error occurs
+        await (await this.related).save()
+    }
Evidence
MainEntity.updateRelatedStatus() uses ActiveRecord .save() on entities extending BaseEntity.
BaseEntity.save() resolves its repository via a static dataSource field, which each
DataSource.initialize() overwrites for every BaseEntity subclass. createTestingConnections()
initializes multiple DataSources in a loop, and this suite executes test logic for all DataSources
via Promise.all, so ActiveRecord calls can be routed to whichever DataSource initialized last (or
be stomped during parallel execution).

test/functional/find-options/select/entity/MainEntity.ts[54-58]
src/repository/BaseEntity.ts[29-33]
src/repository/BaseEntity.ts[51-54]
src/repository/BaseEntity.ts[112-119]
src/data-source/DataSource.ts[779-786]
test/utils/test-utils.ts[388-397]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 functional test entities extend `BaseEntity` and use `.save()` / `.reload()` inside a suite that creates multiple `DataSource`s and runs per-`DataSource` tests via `Promise.all`. Because `BaseEntity` stores a static `DataSource` per entity class, those ActiveRecord calls can be executed against the wrong `DataSource` (typically whichever initialized last), making the tests flaky or incorrect.
### Issue Context
- ActiveRecord methods on `BaseEntity` resolve repositories from a static `dataSource`.
- Each `DataSource.initialize()` overwrites that static for all `BaseEntity` subclasses.
- The test suite runs the same assertions across multiple initialized `DataSource`s.
### Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[1-59]
- test/functional/find-options/select/entity/RelatedEntity.ts[1-20]
- test/functional/find-options/select/entity/OptionA.ts[1-16]
- test/functional/find-options/select/entity/OptionB.ts[1-16]
- test/functional/find-options/select/find-options-select.test.ts[191-229]
### Suggested approach
1. Remove `extends BaseEntity` (and `BaseEntity` imports) from the new test entities.
2. Update `MainEntity.updateRelatedStatus` to accept an `EntityManager` (or `DataSource`) and use `manager.save(...)` instead of `this.save()` / `(await this.related).save()`.
- e.g. `async updateRelatedStatus(manager: EntityManager) { const related = await this.related; related.status = true; await manager.save(this); await manager.save(related); }`
3. Replace `.reload()` calls in the tests with `dataSource.manager.findOneByOrFail(...)` (or `findOne(...)` + assert) to re-fetch state from the correct `DataSource`.
4. Keep the test semantics (eager vs non-eager load) the same, but ensure *all* persistence operations go through the per-iteration `dataSource.manager`/repositories.

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


7. ActiveRecord DS mismatch 🐞 Bug ⛯ Reliability
Description
New functional tests introduce BaseEntity entities and call .save()/.reload() while the suite
runs across multiple DataSources (often in parallel). BaseEntity uses a static DataSource set
during DataSource.initialize(), so with multiple initialized DataSources this can execute against
the wrong connection, causing flaky or incorrect test behavior.
Code

test/functional/find-options/select/entity/MainEntity.ts[R54-58]

+    async updateRelatedStatus() {
+        ;(await this.related).status = true
+        await this.save() // This is where the error occurs
+        await (await this.related).save()
+    }
Evidence
MainEntity.updateRelatedStatus() uses ActiveRecord .save() on entities extending BaseEntity.
BaseEntity.save() resolves its repository via a static dataSource field, which each
DataSource.initialize() overwrites for every BaseEntity subclass. createTestingConnections()
initializes multiple DataSources in a loop, and this suite executes test logic for all DataSources
via Promise.all, so ActiveRecord calls can be routed to whichever DataSource initialized last (or
be stomped during parallel execution).

test/functional/find-options/select/entity/MainEntity.ts[54-58]
src/repository/BaseEntity.ts[29-33]
src/repository/BaseEntity.ts[51-54]
src/repository/BaseEntity.ts[112-119]
src/data-source/DataSource.ts[779-786]
test/utils/test-utils.ts[388-397]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 functional test entities extend `BaseEntity` and use `.save()` / `.reload()` inside a suite that creates multiple `DataSource`s and runs per-`DataSource` tests via `Promise.all`. Because `BaseEntity` stores a static `DataSource` per entity class, those ActiveRecord calls can be executed against the wrong `DataSource` (typically whichever initialized last), making the tests flaky or incorrect.
### Issue Context
- ActiveRecord methods on `BaseEntity` resolve repositories from a static `dataSource`.
- Each `DataSource.initialize()` overwrites that static for all `BaseEntity` subclasses.
- The test suite runs the same assertions across multiple initialized `DataSource`s.
### Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[1-59]
- test/functional/find-options/select/entity/RelatedEntity.ts[1-20]
- test/functional/find-options/select/entity/OptionA.ts[1-16]
- test/functional/find-options/select/entity/OptionB.ts[1-16]
- test/functional/find-options/select/find-options-select.test.ts[191-229]
### Suggested approach
1. Remove `extends BaseEntity` (and `BaseEntity` imports) from the new test entities.
2. Update `MainEntity.updateRelatedStatus` to accept an `EntityManager` (or `DataSource`) and use `manager.save(...)` instead of `this.save()` / `(await this.related).save()`.
- e.g. `async updateRelatedStatus(manager: EntityManager) { const related = await this.related; related.status = true; await manager.save(this); await manager.save(related); }`
3. Replace `.reload()` calls in the tests with `dataSource.manager.findOneByOrFail(...)` (or `findOne(...)` + assert) to re-fetch state from the correct `DataSource`.
4. Keep the test semantics (eager vs non-eager load) the same, but ensure *all* persistence operations go through the per-iteration `dataSource.manager`/repositories.

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



Remediation recommended

8. Potential wasted relation-id loads 🐞 Bug ➹ Performance ⭐ New
Description
After this PR, persistence-disabled owning relations are ignored during join-column diffing, but
SubjectDatabaseEntityLoader still loads relation ids for them when present. This likely adds
avoidable query work during saves/updates involving eagerly loaded persistence:false relations.
Code

src/persistence/SubjectChangedColumnsComputer.ts[R225-230]

        subject.metadata.relationsWithJoinColumns.forEach((relation) => {
+            if (relation.persistenceEnabled === false) return
+
            // get the related entity from the persisted entity
            let relatedEntity = relation.getEntityValue(subject.entity!)
Evidence
The PR makes persistence-disabled relations irrelevant for join-column diffing, but the database
loader still collects relation paths for all defined relations (including persistence-disabled ones)
and requests their ids via loadRelationIds. Filtering these out would reduce work consistent with
the new behavior.

src/persistence/SubjectChangedColumnsComputer.ts[225-233]
src/persistence/SubjectDatabaseEntityLoader.ts[68-84]

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

### Issue description
`SubjectDatabaseEntityLoader` loads relation ids for any relation that is defined (not `undefined`) on the entity. After the PR, persistence-disabled owning relations are skipped during join-column diffing, making those loaded ids likely unnecessary.

### Issue Context
The PR introduced a `persistenceEnabled` guard in `computeDiffRelationalColumns`, but the database loader’s relation-id loading logic has no such guard.

### Fix Focus Areas
- src/persistence/SubjectDatabaseEntityLoader.ts[68-85]
- (reference) src/persistence/SubjectChangedColumnsComputer.ts[225-233]

### Suggested change
When iterating `subject.metadata.relations` to build `loadRelationPropertyPaths` for `save`/`soft-remove`/`recover`, skip relations with `relation.persistenceEnabled === false`.

### Notes
Keep behavior for `remove` under consideration separately, since it currently loads many-to-many relation ids for cleanup.

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


9. Noisy persistence:false comment 📘 Rule violation ⛯ Reliability
Description
A conversational inline comment was added in a new entity definition, which is likely to become
stale and reads like debugging/AI-generated noise. This should be removed or replaced with a
concise, issue-referencing comment.
Code

test/functional/find-options/select/entity/MainEntity.ts[R24-28]

+    @OneToOne(() => OptionA, (a) => a.main, {
+        lazy: true,
+        createForeignKeyConstraints: false,
+        persistence: false, // This should prevent the error, but doesn't when eager loaded
+    })
Evidence
PR Compliance requires avoiding AI-like/sloppy comments; the added inline note is conversational and
describes historical behavior instead of stable intent.

Rule 4: Remove AI-generated noise
test/functional/find-options/select/entity/MainEntity.ts[24-28]

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

## Issue description
An inline comment (`This should prevent the error, but doesn&amp;#x27;t when eager loaded`) is conversational and likely to become stale, which violates the repo guideline to avoid AI-generated noise / slop.
## Issue Context
This appears to be an issue-fix PR; if a comment is needed, it should be a concise regression reference (e.g., `#11905`) rather than a narrative.
## Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[24-28]

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


10. Postgres-only regression test 🐞 Bug ⛯ Reliability
Description
The new lazy-relations regression test is restricted to Postgres, even though the underlying
persistenceEnabled logic change is in core, driver-agnostic persistence code. This reduces
confidence that the fix works consistently across other SQL drivers that support the same feature
surface (lazy relations, join columns).
Code

test/functional/find-options/select-lazy/find-options-select-lazy-relations.test.ts[R15-20]

+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                __dirname,
+                enabledDrivers: ["postgres"],
+            })),
Evidence
The new test suite explicitly limits execution to Postgres only. Meanwhile, the code paths changed
(ColumnMetadata.getEntityValueMap and SubjectChangedColumnsComputer.computeDiffColumns) are in
shared persistence/metadata code and not guarded per-driver, so restricting the test reduces
multi-driver regression coverage.

test/functional/find-options/select-lazy/find-options-select-lazy-relations.test.ts[14-22]
src/persistence/SubjectChangedColumnsComputer.ts[60-78]
src/metadata/ColumnMetadata.ts[718-732]
test/functional/persistence/persistence-disabled-relation/persistence-disabled-relation.test.ts[12-20]

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 regression test under `find-options/select-lazy` is limited to Postgres only. Since the fix changes shared persistence/metadata logic, limiting the test reduces regression detection on other drivers.
### Issue Context
There is already a cross-driver test for `persistence: false` behavior in `test/functional/persistence/persistence-disabled-relation`, but the specific lazy-relation + `relations: {...}` reproduction is only being exercised on Postgres.
### Fix Focus Areas
- test/functional/find-options/select-lazy/find-options-select-lazy-relations.test.ts[14-22]
- test/functional/persistence/persistence-disabled-relation/persistence-disabled-relation.test.ts[12-20]
- src/persistence/SubjectChangedColumnsComputer.ts[60-78]
- src/metadata/ColumnMetadata.ts[718-732]

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


View more (7)
11. #11905 not referenced 📘 Rule violation ✓ Correctness
Description
This PR adds functional tests for an issue fix but does not include an issue reference comment
(e.g., #11905) in the new test block. This reduces traceability from the regression test back to
the originating issue.
Code

test/functional/find-options/select/find-options-select.test.ts[R191-229]

+    it("should works when relations are not eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+
+                await entity.updateRelatedStatus()
+                await entity.reload()
+
+                expect((await entity.related).status).to.be.true
+            }),
+        ))
+
+    it("should update related entity when relation is eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+                const reloaded = await dataSource.manager.findOne(MainEntity, {
+                    where: { id: entity.id },
+                    relations: { optionA: true, optionB: true, related: true },
+                })
+
+                await reloaded!.updateRelatedStatus()
+                await reloaded!.reload()
+
+                expect((await reloaded!.related).status).to.be.true
+            }),
+        ))
Evidence
Compliance ID 3 requires issue fixes to live in the functional test suite with an issue reference
comment when applicable; the newly added tests contain no #11905 reference/comment in the added
block.

Rule 3: Prefer functional tests over per-issue tests
test/functional/find-options/select/find-options-select.test.ts[191-229]

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

## Issue description
Functional regression tests were added for an issue fix but do not include an issue reference comment, reducing traceability.
## Issue Context
Compliance requires issue fixes in `test/functional` to include an issue reference comment when applicable.
## Fix Focus Areas
- test/functional/find-options/select/find-options-select.test.ts[191-229]

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


12. #11905 not referenced 📘 Rule violation ✓ Correctness
Description
This PR adds functional tests for an issue fix but does not include an issue reference comment
(e.g., #11905) in the new test block. This reduces traceability from the regression test back to
the originating issue.
Code

test/functional/find-options/select/find-options-select.test.ts[R191-229]

+    it("should works when relations are not eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+
+                await entity.updateRelatedStatus()
+                await entity.reload()
+
+                expect((await entity.related).status).to.be.true
+            }),
+        ))
+
+    it("should update related entity when relation is eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+                const reloaded = await dataSource.manager.findOne(MainEntity, {
+                    where: { id: entity.id },
+                    relations: { optionA: true, optionB: true, related: true },
+                })
+
+                await reloaded!.updateRelatedStatus()
+                await reloaded!.reload()
+
+                expect((await reloaded!.related).status).to.be.true
+            }),
+        ))
Evidence
Compliance ID 3 requires issue fixes to live in the functional test suite with an issue reference
comment when applicable; the newly added tests contain no #11905 reference/comment in the added
block.

Rule 3: Prefer functional tests over per-issue tests
test/functional/find-options/select/find-options-select.test.ts[191-229]

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

## Issue description
Functional regression tests were added for an issue fix but do not include an issue reference comment, reducing traceability.
## Issue Context
Compliance requires issue fixes in `test/functional` to include an issue reference comment when applicable.
## Fix Focus Areas
- test/functional/find-options/select/find-options-select.test.ts[191-229]

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


13. expect added, style inconsistent 📘 Rule violation ⛯ Reliability
Description
This test suite primarily uses should assertions, but the PR introduces expect assertions and
imports expect from chai, creating inconsistent assertion style within the same file. This
violates the requirement to avoid style inconsistent with the file.
Code

test/functional/find-options/select/find-options-select.test.ts[R12-14]

+import { MainEntity } from "./entity/MainEntity"
+import { RelatedEntity } from "./entity/RelatedEntity"
+import { expect } from "chai"
Evidence
Compliance ID 4 prohibits inconsistent style; this file already uses should assertions, but the PR
adds expect import and expect(...) assertions in the new tests.

Rule 4: Remove AI-generated noise
test/functional/find-options/select/find-options-select.test.ts[51-80]
test/functional/find-options/select/find-options-select.test.ts[12-14]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 file mixes `chai` assertion styles (`should` and `expect`), which is inconsistent with the existing file style.
## Issue Context
Most tests in this file already use `should` (e.g., `categories.should.be.eql(...)`). The PR adds `expect` imports and `expect(...)` assertions.
## Fix Focus Areas
- test/functional/find-options/select/find-options-select.test.ts[12-14]
- test/functional/find-options/select/find-options-select.test.ts[191-229]

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


14. Noisy persistence:false comment 📘 Rule violation ⛯ Reliability
Description
A conversational inline comment was added in a new entity definition, which is likely to become
stale and reads like debugging/AI-generated noise. This should be removed or replaced with a
concise, issue-referencing comment.
Code

test/functional/find-options/select/entity/MainEntity.ts[R24-28]

+    @OneToOne(() => OptionA, (a) => a.main, {
+        lazy: true,
+        createForeignKeyConstraints: false,
+        persistence: false, // This should prevent the error, but doesn't when eager loaded
+    })
Evidence
PR Compliance requires avoiding AI-like/sloppy comments; the added inline note is conversational and
describes historical behavior instead of stable intent.

Rule 4: Remove AI-generated noise
test/functional/find-options/select/entity/MainEntity.ts[24-28]

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

## Issue description
An inline comment (`This should prevent the error, but doesn&amp;amp;#x27;t when eager loaded`) is conversational and likely to become stale, which violates the repo guideline to avoid AI-generated noise / slop.
## Issue Context
This appears to be an issue-fix PR; if a comment is needed, it should be a concise regression reference (e.g., `#11905`) rather than a narrative.
## Fix Focus Areas
- test/functional/find-options/select/entity/MainEntity.ts[24-28]

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


15. expect added, style inconsistent 📘 Rule violation ⛯ Reliability
Description
This test suite primarily uses should assertions, but the PR introduces expect assertions and
imports expect from chai, creating inconsistent assertion style within the same file. This
violates the requirement to avoid style inconsistent with the file.
Code

test/functional/find-options/select/find-options-select.test.ts[R12-14]

+import { MainEntity } from "./entity/MainEntity"
+import { RelatedEntity } from "./entity/RelatedEntity"
+import { expect } from "chai"
Evidence
Compliance ID 4 prohibits inconsistent style; this file already uses should assertions, but the PR
adds expect import and expect(...) assertions in the new tests.

Rule 4: Remove AI-generated noise
test/functional/find-options/select/find-options-select.test.ts[51-80]
test/functional/find-options/select/find-options-select.test.ts[12-14]
test/functional/find-options/select/find-options-select.test.ts[191-229]

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 file mixes `chai` assertion styles (`should` and `expect`), which is inconsistent with the existing file style.
## Issue Context
Most tests in this file already use `should` (e.g., `categories.should.be.eql(...)`). The PR adds `expect` imports and `expect(...)` assertions.
## Fix Focus Areas
- test/functional/find-options/select/find-options-select.test.ts[12-14]
- test/functional/find-options/select/find-options-select.test.ts[191-229]

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


16. #11905 not referenced 📘 Rule violation ✓ Correctness
Description
This PR adds functional tests for an issue fix but does not include an issue reference comment
(e.g., #11905) in the new test block. This reduces traceability from the regression test back to
the originating issue.
Code

test/functional/find-options/select/find-options-select.test.ts[R191-229]

+    it("should works when relations are not eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+
+                await entity.updateRelatedStatus()
+                await entity.reload()
+
+                expect((await entity.related).status).to.be.true
+            }),
+        ))
+
+    it("should update related entity when relation is eagerly loaded", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const related = new RelatedEntity()
+                related.status = false
+                await dataSource.manager.save(related)
+                const entity = new MainEntity()
+                entity.optionId = null
+                entity.relatedId = related.id
+                await dataSource.manager.save(entity)
+                const reloaded = await dataSource.manager.findOne(MainEntity, {
+                    where: { id: entity.id },
+                    relations: { optionA: true, optionB: true, related: true },
+                })
+
+                await reloaded!.updateRelatedStatus()
+                await reloaded!.reload()
+
+                expect((await reloaded!.related).status).to.be.true
+            }),
+        ))
Evidence
Compliance ID 3 requires issue fixes to live in the functional test suite with an issue reference
comment when applicable; the newly added tests contain no #11905 reference/comment in the added
block.

Rule 3: Prefer functional tests over per-issue tests
test/functional/find-options/select/find-options-select.test.ts[191-229]

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

## Issue description
Functional regression tests were added for an issue fix but do not include an issue reference comment, reducing traceability.
## Issue Context
Compliance requires issue fixes in `test/functional` to include an issue reference comment when applicable.
## Fix Focus Areas
- test/functional/find-options/select/find-options-select.test.ts[191-229]

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


17. expect added, style inconsistent 📘 Rule violation ⛯ Reliability
Description
This test suite primarily uses should assertions, but the PR introduces expect assertions and
imports expect from chai, creating inconsistent assertion style withi...

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

Copy link
Copy Markdown

Persistent review updated to latest commit 681f0d2

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

Copy link
Copy Markdown

Persistent review updated to latest commit 38484c6

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

Copy link
Copy Markdown

Persistent review updated to latest commit ec10c76

@gioboa
gioboa force-pushed the fix/11905 branch 3 times, most recently from d984914 to 3328582 Compare February 11, 2026 10:37
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit ea1055d

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

Copy link
Copy Markdown

Persistent review updated to latest commit 3328582

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

Copy link
Copy Markdown

Persistent review updated to latest commit d984914

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

Copy link
Copy Markdown

Persistent review updated to latest commit babc9c0

@gioboa
gioboa requested review from G0maa and alumni February 11, 2026 13:58
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit bc3feac

Comment on lines 225 to 228
subject.metadata.relationsWithJoinColumns.forEach((relation) => {
if (relation.persistenceEnabled === false) return

// get the related entity from the persisted entity

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Cascade ignores persistence flag 🐞 Bug ✓ Correctness

With the new persistenceEnabled guard, join columns won’t be updated from relations marked
persistence:false, but cascade insert/update can still run for those relations. This can persist the
related entity while leaving the owning FK unchanged, resulting in surprising partial persistence
(relationship not written).
Agent Prompt
### Issue description
`computeDiffRelationalColumns` now skips join-column diffing for relations with `persistenceEnabled === false`. However, `CascadesSubjectBuilder` can still cascade insert/update/soft-remove/recover through those relations, potentially persisting related entities without updating the owning-side FK/join columns, leading to partial/inconsistent persistence.

### Issue Context
Other persistence builders (e.g., many-to-many/one-to-many) already respect `persistenceEnabled` by skipping such relations. Cascades should be consistent with this contract.

### Fix Focus Areas
- src/persistence/subject-builder/CascadesSubjectBuilder.ts[23-46]
- (reference) src/persistence/SubjectChangedColumnsComputer.ts[225-233]

### Suggested change
Add a guard inside the cascades loop:
- If `relation.persistenceEnabled === false`, skip building cascade subjects for that relation.

### Notes
Consider whether the guard should apply to all operation types handled in `CascadesSubjectBuilder` (save/soft-remove/recover), since those are the cascade types supported there.

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

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 81.136% (+0.005%) from 81.131%
when pulling bc3feac on gioboa:fix/11905
into eacc2ca on typeorm:master.

@gioboa
gioboa merged commit f5cea95 into typeorm:master Feb 14, 2026
38 checks passed
@gioboa
gioboa deleted the fix/11905 branch February 14, 2026 14:25
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Bug: "multiple assignments to same column" error when eager loading relations that share column

5 participants