Skip to content

fix: soft deletion should not update the already soft deleted rows - #10705

Merged
gioboa merged 19 commits into
typeorm:masterfrom
hassanmehdi98:fix/redundant-updates-on-soft-delete
Jan 18, 2026
Merged

gioboa merged 19 commits into
typeorm:masterfrom
hassanmehdi98:fix/redundant-updates-on-soft-delete

Conversation

@hassanmehdi98

@hassanmehdi98 hassanmehdi98 commented Feb 14, 2024 •

Copy link
Copy Markdown
Contributor

Description of change

Current Behavior

After a soft deletion, if you do a soft delete again with the same condition, it updates the deleted at column of the previously soft deleted rows as well.

New Behavior

Rows that were already soft deleted previously will be excluded from further soft deletion

Fixes #10389

Pull-Request Checklist

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

@hassanmehdi98 hassanmehdi98 changed the title fix: fix issue where soft deletion also updates the already soft deleted rows fix: soft deletion should not update the already soft deleted rows Feb 14, 2024
@hassanmehdi98

Copy link
Copy Markdown
Contributor Author

I don't understand why this test fails, any help? I can see this failing in several other PRs as well.
image

@hassanmehdi98
hassanmehdi98 requested a review from AmauryLiet March 1, 2024 09:30

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

Thank you @hassanmehdi98 for your help
I added this PR to our board for the next releases.

@gioboa gioboa added the size-m label Jan 24, 2025
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 6eb9c26

CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify queryType is set correctly

Refactor the condition to explicitly check for the "restore" query type instead
of relying on the else case of a ternary operator, improving code clarity.

src/query-builder/SoftDeleteQueryBuilder.ts [494-504]

 // only update rows that are not already soft deleted
+const isRestore = this.expressionMap.queryType === "restore"
 this.expressionMap.wheres.push({
     type: "and",
     condition: `${this.escape(
         metadata.deleteDateColumn.databaseName,
-    )} IS ${
-        this.expressionMap.queryType === "soft-delete"
-            ? "NULL"
-            : "NOT NULL"
-    }`,
+    )} IS ${isRestore ? "NOT NULL" : "NULL"}`,
 })
  • Apply / Chat
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies that the logic depends on queryType, but the PR's new tests already verify the behavior for both soft-delete and restore, confirming the implementation is correct. The proposed code is a minor stylistic improvement for explicitness but does not change the functionality.

Low
  • More

Previous suggestions

Suggestions up to commit 31cc389
CategorySuggestion                                                                                                                                    Impact
Possible issue
Verify queryType for restore operations

Verify that this.expressionMap.queryType is correctly set for restore
operations, or refactor the conditional logic to be more explicit about handling
the 'restore' case.

src/query-builder/SoftDeleteQueryBuilder.ts [494-504]

 // only update rows that are not already soft deleted
+const isRestore = this.expressionMap.queryType === "restore"
 this.expressionMap.wheres.push({
     type: "and",
     condition: `${this.escape(
         metadata.deleteDateColumn.databaseName,
-    )} IS ${
-        this.expressionMap.queryType === "soft-delete"
-            ? "NULL"
-            : "NOT NULL"
-    }`,
+    )} IS ${isRestore ? "NOT NULL" : "NULL"}`,
 })
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies a critical logic path for soft-delete vs. restore, but the existing code is correct as queryType is set to 'restore' for restore operations. The proposed change is a minor readability improvement at best, and the PR already includes tests that verify this exact behavior.

Low
✅ Suggestions up to commit ea3285c
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use database column name instead
Suggestion Impact:The suggestion was implemented. The commit changed from using `propertyName` to `databaseName` as recommended. Additionally, the implementation added proper escaping via `this.escape()` and removed the `getWhereCondition()` wrapper, directly assigning the condition string. The core intent of using the database column name instead of the property name was fully addressed.

code diff:

-            condition: this.getWhereCondition(
-                `${metadata.deleteDateColumn.propertyName} IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Replace metadata.deleteDateColumn.propertyName with
metadata.deleteDateColumn.databaseName to ensure the correct database column
name is used in the WHERE condition, accommodating different naming strategies.

src/query-builder/SoftDeleteQueryBuilder.ts [494-504]

 // only update rows that are not already soft deleted
 this.expressionMap.wheres.push({
     type: "and",
     condition: this.getWhereCondition(
-        `${metadata.deleteDateColumn.propertyName} IS ${
+        `${metadata.deleteDateColumn.databaseName} IS ${
             this.expressionMap.queryType === "soft-delete"
                 ? "NULL"
                 : "NOT NULL"
         }`,
     ),
 })
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that using propertyName can lead to incorrect SQL if a naming strategy is in use, and proposes using databaseName which is the correct approach for building raw SQL fragments.

Medium
✅ Suggestions up to commit 3b0d2ab
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use database column name instead
Suggestion Impact:The commit implemented the core suggestion by replacing `metadata.deleteDateColumn.propertyName` with `metadata.deleteDateColumn.databaseName` and wrapping it with `this.escape()`. However, the commit also removed the `this.getWhereCondition()` wrapper, directly embedding the escaped database name in the condition string instead.

code diff:

-            condition: this.getWhereCondition(
-                `${metadata.deleteDateColumn.propertyName} IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Replace propertyName with databaseName when constructing the where condition for
soft-delete/restore to ensure the correct database column is used.

src/query-builder/SoftDeleteQueryBuilder.ts [494-504]

 // only update rows that are not already soft deleted
 this.expressionMap.wheres.push({
     type: "and",
     condition: this.getWhereCondition(
-        `${metadata.deleteDateColumn.propertyName} IS ${
+        `${this.escape(metadata.deleteDateColumn.databaseName)} IS ${
             this.expressionMap.queryType === "soft-delete"
                 ? "NULL"
                 : "NOT NULL"
         }`,
     ),
 })
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a bug where using propertyName would generate invalid SQL if the column name differs from the property name, which is a common scenario.

Medium
✅ Suggestions up to commit 60eb587
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use database column name
Suggestion Impact:The commit implemented the core suggestion by changing from propertyName to databaseName (line 16). However, the implementation differs from the suggestion: it removed the getWhereCondition() wrapper and added this.escape() for proper SQL escaping, and also simplified the code structure by removing the template literal nesting.

code diff:

-            condition: this.getWhereCondition(
-                `${
-                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                        ?.propertyName
-                } IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Replace propertyName with databaseName when constructing the where condition.
This ensures the correct database column name is used in the SQL query,
preventing potential errors when a naming strategy is applied.

src/query-builder/SoftDeleteQueryBuilder.ts [494-507]

 // only update rows that are not already soft deleted
 this.expressionMap.wheres.push({
     type: "and",
     condition: this.getWhereCondition(
         `${
             this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                ?.propertyName
+                ?.databaseName
         } IS ${
             this.expressionMap.queryType === "soft-delete"
                 ? "NULL"
                 : "NOT NULL"
         }`,
     ),
 })
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that propertyName is used instead of databaseName, which would cause the query to fail if a naming strategy is used that changes property names to different column names. This is a valid and important bug fix.

Medium
Suggestions up to commit 4877b89
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Use database column name instead
Suggestion Impact:The commit implemented the core suggestion by replacing `metadata.deleteDateColumn.propertyName` with `metadata.deleteDateColumn.databaseName` and wrapping it with `this.escape()`. However, the commit also removed the `this.getWhereCondition()` wrapper, directly embedding the escaped database name in the condition string instead.

code diff:

-            condition: this.getWhereCondition(
-                `${metadata.deleteDateColumn.propertyName} IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Replace propertyName with databaseName in the WHERE condition to use the correct
database column name in the generated SQL query.

src/query-builder/SoftDeleteQueryBuilder.ts [494-507]

 // only update rows that are not already soft deleted
 this.expressionMap.wheres.push({
     type: "and",
     condition: this.getWhereCondition(
         `${
             this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                ?.propertyName
+                ?.databaseName
         } IS ${
             this.expressionMap.queryType === "soft-delete"
                 ? "NULL"
                 : "NOT NULL"
         }`,
     ),
 })
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug where propertyName is used instead of databaseName for a raw SQL query fragment, which would cause an error if the database column name and entity property name are different.

High

@pkg-pr-new

pkg-pr-new Bot commented Jan 2, 2026 •

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

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

commit: 6eb9c26

@coveralls

coveralls commented Jan 2, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.936% (+0.004%) from 80.932%
when pulling 3b0d2ab on hassanmehdi98:fix/redundant-updates-on-soft-delete
into c70a65b on typeorm:master.

@gioboa
gioboa requested review from alumni, dlhck, michaelbromley and naorpeled and removed request for AmauryLiet January 2, 2026 15:13

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

I renamed the test file and added the missing OR condition test.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

(Review updated until commit 4877b89)

🐞 Bugs (1) 📘 Rule Violations (1) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Remediation Recommended

1. `deleteDateColumn?.propertyName` may be undefined 📘 Rule Violation
Description
• The code accesses deleteDateColumn?.propertyName using optional chaining, which can result in
  undefined being interpolated into the SQL string
• While deleteDateColumn existence is validated earlier (line 452-454), the optional chaining
  operator suggests uncertainty about the property's availability
• If propertyName is undefined, the generated SQL would contain 'undefined IS NULL', which could
  cause database errors or unexpected behavior

correctness

Code

src/query-builder/SoftDeleteQueryBuilder.ts[R499-500]

+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
Evidence
The compliance rule requires explicit handling of edge cases including null and empty values. The
code uses optional chaining on line 499-500 to access deleteDateColumn?.propertyName, but earlier
validation at line 452-454 already confirms deleteDateColumn exists. The optional chaining
suggests the property might be undefined, yet there's no explicit handling for this case. If
propertyName is undefined, it would be interpolated into the SQL string as the literal text
'undefined'.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/SoftDeleteQueryBuilder.ts[499-500]
src/query-builder/SoftDeleteQueryBuilder.ts[452-454]

Agent Prompt
## Issue description
The code uses optional chaining on `deleteDateColumn?.propertyName` which could result in `undefined` being interpolated into the SQL string, potentially causing database errors.

## Issue Context
The `deleteDateColumn` existence is already validated at line 452-454, so the optional chaining may be unnecessary. However, if `propertyName` itself can be undefined, this needs explicit handling.

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[499-500]

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


2. Missing restore operation test coverage 🐞 Bug
Description
• The PR adds logic to prevent restore operations from updating non-deleted rows (lines 502-504
  check for 'IS NOT NULL')
• The test file only includes tests for soft-delete operations, not restore operations
• This leaves the restore branch of the new WHERE clause logic untested
• Without tests, regressions in restore behavior could go undetected

reliability

Code

test/github-issues/10389/issue-10389.test.ts[R11-140]

+describe("github issues > #10389 softDelete should not update already deleted rows", () => {
+    let dataSources: DataSource[]
+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                entities: [__dirname + "/entity/*{.js,.ts}"],
+                schemaCreate: true,
+                dropSchema: true,
+            })),
+    )
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should only soft delete rows that are not soft deleted previously", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                // tests go here
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { name: "Hassan", company: "test1" },
+                    { name: "Nav", company: "test1" },
+                ]
+                const batch1Users = batch1UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 1
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch1Users)
+
+                // soft delete users with company test1
+                const del1 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users with the same company test1
+                const batch2UsersData = [
+                    { name: "Omer", company: "test1" },
+                    { name: "Daniyal", company: "test1" },
+                    { name: "Salman", company: "test1" },
+                    { name: "Shahzaib", company: "test1" },
+                ]
+                const batch2Users = batch2UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 3
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch2Users)
+
+                // soft delete users again with company test1
+                const del2 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                // now affected rows should be equal to 4 and not 6, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+            }),
+        ))
+
+    it("should correctly handle OR conditions in softDelete and not update already deleted rows", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { id: 10, name: "User 10", company: "comp1" },
+                    { id: 11, name: "User 11", company: "comp1" },
+                ]
+                const batch1Users = batch1UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch1Users)
+
+                // soft delete users with ID 10 OR 11
+                const del1 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                ])
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users
+                const batch2UsersData = [
+                    { id: 12, name: "User 12", company: "comp1" },
+                    { id: 13, name: "User 13", company: "comp1" },
+                ]
+                const batch2Users = batch2UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch2Users)
+
+                // soft delete users again with ID 10 OR 11 OR 12 OR 13
+                const del2 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                    { id: 12 },
+                    { id: 13 },
+                ])
+
+                // now affected rows should be equal to 2 (batch2) and not 4, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+
+                const softDeletedUsers = await manager.find(User, {
+                    where: [{ id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }],
+                    withDeleted: true,
+                })
+                expect(softDeletedUsers.length).to.be.eql(4)
+                softDeletedUsers.forEach((user) => {
+                    expect(user.deletedAt).to.be.instanceOf(Date)
+                })
+            }),
+        ))
+})
Evidence
The test file contains two test cases (lines 24-77 and 79-139) that only test softDelete operations.
The code modification in SoftDeleteQueryBuilder.ts shows that restore operations use a different
condition ('IS NOT NULL' instead of 'IS NULL'), but this code path is never exercised in the new
test file. Existing tests in
test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts do test restore
operations, but they don't specifically verify that restore only affects already-deleted rows.

src/query-builder/SoftDeleteQueryBuilder.ts[502-504]
test/github-issues/10389/issue-10389.test.ts[24-77]
test/github-issues/10389/issue-10389.test.ts[79-139]

Agent Prompt
## Issue Description
The test file for issue #10389 only tests soft-delete operations but doesn't test restore operations. The code change affects both soft-delete and restore operations, so both should be tested.

## Issue Context
The modification in SoftDeleteQueryBuilder.ts adds a WHERE clause that filters rows based on their deletion state:
- For soft-delete: adds 'deletedAt IS NULL' to only delete non-deleted rows
- For restore: adds 'deletedAt IS NOT NULL' to only restore already-deleted rows

The test file only verifies the soft-delete behavior.

## Fix Focus Areas
Add test cases to verify restore operation behavior:
- test/github-issues/10389/issue-10389.test.ts[140-140]

The new tests should:
1. Create and soft-delete some rows
2. Create additional non-deleted rows with the same criteria
3. Call restore() with criteria matching both deleted and non-deleted rows
4. Verify that only the previously deleted rows are restored (affected count should match only the deleted rows)
5. Include a test case with OR conditions similar to the existing soft-delete test

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


Grey Divider


Previous review results

Results up to commit 7c5ee6d


🐞 Bugs (3) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider
Action Required
1. Duplicate WHERE conditions on repeated getQuery calls 🐞 Bug
Description
• The WHERE condition filtering already deleted/restored rows is added inside
  createUpdateExpression() by pushing to this.expressionMap.wheres
• Since createUpdateExpression() is called from getQuery(), each invocation of getQuery()
  appends another WHERE condition to the array
• This causes duplicate conditions like 'AND deletedAt IS NULL AND deletedAt IS NULL' if the query
  builder is reused or methods like printSql(), getSql(), or getQueryAndParameters() are called
  multiple times
• The bug silently produces malformed SQL that may fail at runtime or produce unexpected results

correctness

Code

src/query-builder/SoftDeleteQueryBuilder.ts[R495-508]

+        // only update rows that are not already soft deleted
+        this.expressionMap.wheres.push({
+            type: "and",
+            condition: this.getWhereCondition(
+                `${
+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
+                } IS ${
+                    this.expressionMap.queryType === "soft-delete"
+                        ? "NULL"
+                        : "NOT NULL"
+                }`,
+            ),
+        })
Evidence
The code modifies query builder state (expressionMap.wheres) inside a method that generates SQL
expressions. The createUpdateExpression method is called from getQuery (line 48), which is a
read-only method that can be invoked multiple times. The UpdateQueryBuilder's createUpdateExpression
method (lines 475-700) does NOT modify expressionMap.wheres, showing this is an anti-pattern. Each
call to getQuery will push another WHERE condition, creating duplicates.

src/query-builder/SoftDeleteQueryBuilder.ts[495-508]
src/query-builder/SoftDeleteQueryBuilder.ts[48]
src/query-builder/UpdateQueryBuilder.ts[475-685]

Agent Prompt
## Issue Description
The WHERE condition that filters already deleted/restored rows is being added inside `createUpdateExpression()`, which is called every time `getQuery()` is invoked. This causes duplicate WHERE conditions to accumulate in `expressionMap.wheres`, leading to malformed SQL.

## Issue Context
- The `createUpdateExpression()` method is called from `getQuery()` (line 48)
- `getQuery()` is a read-only method that can be called multiple times (via `getSql()`, `printSql()`, `getQueryAndParameters()`, etc.)
- Each call appends another WHERE condition to the array
- The `UpdateQueryBuilder` does NOT modify `expressionMap.wheres` in its `createUpdateExpression()` method, showing this is an anti-pattern

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[495-508] - Remove the WHERE condition push from createUpdateExpression
- src/query-builder/SoftDeleteQueryBuilder.ts[180-244] - Consider adding the WHERE condition in the where() method or a dedicated initialization method
- src/query-builder/SoftDeleteQueryBuilder.ts[48-52] - Ensure the WHERE condition is added before the first getQuery() call but not on subsequent calls

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



Remediation Recommended
2. Inconsistent column reference using propertyName instead of databaseName 🐞 Bug
Description
• The WHERE condition uses deleteDateColumn.propertyName to reference the column
• The UPDATE SET clause in the same method uses deleteDateColumn.databaseName (lines 463, 469)
• While replacePropertyNamesForTheWholeQuery() converts property names to database names, this
  inconsistency creates fragility
• If the property name differs from the database column name (e.g., deletedAt vs deleted_at),
  the WHERE condition may reference the wrong column before transformation

correctness

Code

src/query-builder/SoftDeleteQueryBuilder.ts[R499-502]

+                `${
+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
+                } IS ${
Evidence
The code shows inconsistent column referencing within the same method. Lines 463 and 469 use
databaseName directly for the UPDATE SET clause, while lines 500-501 use propertyName for the WHERE
condition. This pattern mismatch suggests the WHERE condition should also use databaseName for
consistency and to avoid relying on downstream transformation logic.

src/query-builder/SoftDeleteQueryBuilder.ts[499-502]
src/query-builder/SoftDeleteQueryBuilder.ts[463-464]
src/query-builder/SoftDeleteQueryBuilder.ts[469-470]

Agent Prompt
## Issue Description
The WHERE condition uses `propertyName` to reference the delete date column, while the UPDATE SET clause uses `databaseName`. This inconsistency creates fragility and potential bugs if property names differ from database column names.

## Issue Context
- Lines 463 and 469 use `metadata.deleteDateColumn.databaseName` for the UPDATE SET clause
- Lines 500-501 use `metadata.deleteDateColumn.propertyName` for the WHERE condition
- While `replacePropertyNamesForTheWholeQuery()` may handle the conversion, it's better to be consistent and explicit
- Using `databaseName` directly is the established pattern in this method

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[499-502] - Change from `propertyName` to `databaseName` to match the pattern used elsewhere in the method

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



Advisory Comments
3. Redundant optional chaining on deleteDateColumn 🐞 Bug
Description
• The code uses optional chaining ?.propertyName on line 500-501
• However, line 453 already checks if deleteDateColumn exists and throws
  MissingDeleteDateColumnError if it's missing
• The optional chaining is redundant and creates confusion about whether the column can actually be
  null at this point
• This makes the code less clear about its invariants

correctness

Code

src/query-builder/SoftDeleteQueryBuilder.ts[R500-501]

+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
Evidence
The code shows a null check at line 453 that throws an error if deleteDateColumn is missing,
guaranteeing it exists at line 500. The optional chaining operator suggests uncertainty about the
column's existence, but the earlier check ensures it's non-null. This redundancy creates confusion
about the actual state of the variable.

src/query-builder/SoftDeleteQueryBuilder.ts[453-455]
src/query-builder/SoftDeleteQueryBuilder.ts[500-501]

Agent Prompt
## Issue Description
The code uses optional chaining `?.propertyName` even though a null check at line 453 guarantees the column exists. This creates confusion about the actual invariants of the code.

## Issue Context
- Line 453 checks `if (!metadata.deleteDateColumn)` and throws an error if it's missing
- This guarantees that `deleteDateColumn` is non-null at line 500
- The optional chaining `?.` suggests the column might be null, contradicting the earlier check
- This makes the code less clear and harder to reason about

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[500-501] - Remove the optional chaining operator and use direct property access (or better yet, change to `databaseName` as per the other finding)

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


Grey Divider

Qodo Logo

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

Copy link
Copy Markdown

Persistent review updated to latest commit 60575b9

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

Copy link
Copy Markdown

Persistent review updated to latest commit 6e8a534

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

Copy link
Copy Markdown

Persistent review updated to latest commit 4877b89

@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 @hassanmehdi98 for your help 👏

@gioboa
gioboa requested a review from alumni January 17, 2026 14:00
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Tests in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The PR adds tests exclusively under test/github-issues/10389/ without adding or updating tests
  in the test/functional directory.
• The compliance rule requires issue fixes to add or update tests in test/functional, with an
  issue reference in the test comment when applicable.
• This violates the preference for functional tests over per-issue tests.
Code

test/github-issues/10389/issue-10389.test.ts[R1-193]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { DataSource } from "../../../src/data-source/DataSource"
+import { expect } from "chai"
+import { User } from "./entity/User"
+import { scheduler } from "node:timers/promises"
+
+describe("github issues > #10389 softDelete should not update already deleted rows", () => {
+    let dataSources: DataSource[]
+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                entities: [__dirname + "/entity/*{.js,.ts}"],
+                schemaCreate: true,
+                dropSchema: true,
+            })),
+    )
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should only soft delete rows that are not soft deleted previously", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                // tests go here
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { name: "Hassan", company: "test1" },
+                    { name: "Nav", company: "test1" },
+                ]
+                const batch1Users = batch1UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 1
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch1Users)
+
+                // soft delete users with company test1
+                const del1 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users with the same company test1
+                const batch2UsersData = [
+                    { name: "Omer", company: "test1" },
+                    { name: "Daniyal", company: "test1" },
+                    { name: "Salman", company: "test1" },
+                    { name: "Shahzaib", company: "test1" },
+                ]
+                const batch2Users = batch2UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 3
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch2Users)
+
+                // soft delete users again with company test1
+                const del2 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                // now affected rows should be equal to 4 and not 6, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+            }),
+        ))
+
+    it("should correctly handle OR conditions in softDelete and not update already deleted rows", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { id: 10, name: "User 10", company: "comp1" },
+                    { id: 11, name: "User 11", company: "comp1" },
+                ]
+                const batch1Users = batch1UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch1Users)
+
+                // soft delete users with ID 10 OR 11
+                const del1 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                ])
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users
+                const batch2UsersData = [
+                    { id: 12, name: "User 12", company: "comp1" },
+                    { id: 13, name: "User 13", company: "comp1" },
+                ]
+                const batch2Users = batch2UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch2Users)
+
+                // soft delete users again with ID 10 OR 11 OR 12 OR 13
+                const del2 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                    { id: 12 },
+                    { id: 13 },
+                ])
+
+                // now affected rows should be equal to 2 (batch2) and not 4, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+
+                const softDeletedUsers = await manager.find(User, {
+                    where: [{ id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }],
+                    withDeleted: true,
+                })
+                expect(softDeletedUsers.length).to.be.eql(4)
+                softDeletedUsers.forEach((user) => {
+                    expect(user.deletedAt).to.be.instanceOf(Date)
+                })
+            }),
+        ))
+
+    it("should only restore rows that are soft deleted previously", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const manager = dataSource.manager
+
+                // create test users
+                const user1 = new User()
+                user1.id = 1
+                user1.name = "User 1"
+                user1.company = "comp1"
+
+                const user2 = new User()
+                user2.id = 2
+                user2.name = "User 2"
+                user2.company = "comp1"
+
+                await manager.save([user1, user2])
+
+                // soft delete user 1
+                await manager.softDelete(User, { id: 1 })
+
+                // user1 is now deleted, user2 is NOT.
+                // Both have company "comp1".
+
+                // Get current state of user 2
+                const user2Before = await manager.findOneBy(User, { id: 2 })
+                expect(user2Before).to.exist
+                const updatedAtBefore = user2Before!.updatedAt
+                const versionBefore = user2Before!.version
+
+                // wait a bit to ensure CURRENT_TIMESTAMP will be different if updated
+                await scheduler.wait(1000)
+
+                // restore users with company comp1
+                const restoreResult = await manager.restore(User, {
+                    company: "comp1",
+                })
+
+                // only user1 should be restored
+                expect(restoreResult.affected).to.be.eql(1)
+
+                const user1After = await manager.findOneBy(User, { id: 1 })
+                expect(user1After!.deletedAt).to.be.null
+
+                const user2After = await manager.findOneBy(User, { id: 2 })
+                expect(user2After!.deletedAt).to.be.null
+                // updateDate and version should NOT have changed for user 2
+                expect(user2After!.updatedAt).to.be.eql(updatedAtBefore)
+                expect(user2After!.version).to.be.eql(versionBefore)
+            }),
+        ))
+})
Evidence
The PR adds comprehensive tests for the soft delete fix, but places them entirely in
test/github-issues/10389/ instead of test/functional/. The compliance checklist (PR Compliance ID 3)
requires issue fixes to stay in the functional test suite. While there are existing soft delete
tests in test/functional/repository/soft-delete/ and test/functional/query-builder/soft-delete/, the
new tests were not added there.

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

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 for issue #10389 are placed in test/github-issues/ instead of the functional test suite, violating the project's testing conventions.

## Issue Context
The project prefers functional tests over per-issue tests. There are existing soft delete test suites in:
- test/functional/repository/soft-delete/
- test/functional/query-builder/soft-delete/

The new tests should be integrated into one of these existing functional test suites with a comment referencing issue #10389.

## Fix Focus Areas
- test/github-issues/10389/issue-10389.test.ts[1-193]
- test/functional/repository/soft-delete/repository-soft-delete.test.ts[1-80]

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


2. Missing documentation for behavior change 📘 Rule violation ✓ Correctness
Description
• The PR changes the behavior of softDelete() and restore() methods to exclude already
  soft-deleted/restored rows.
• This is a user-facing behavior change that affects the affected count returned by these
  operations.
• The PR description marks documentation as N/A, but the behavior change should be documented.
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R494-504]

+        // only update rows that are not already soft deleted
+        this.expressionMap.wheres.push({
+            type: "and",
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,
+        })
Evidence
The compliance checklist requires documentation updates for user-facing changes. The PR modifies the
behavior of softDelete and restore operations by filtering out already soft-deleted/restored rows.
This changes the affected count returned by these operations, which is a user-facing API change.
The existing documentation in docs/docs/query-builder/4-delete-query-builder.md and
docs/docs/working-with-entity-manager/6-repository-api.md does not describe this filtering behavior.

Rule 2: Docs updated for user-facing changes
src/query-builder/SoftDeleteQueryBuilder.ts[494-504]

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 behavior change where softDelete/restore operations now filter out already soft-deleted/restored rows needs to be documented.

## Issue Context
This is a user-facing behavior change that affects:
1. The `affected` count returned by softDelete() and restore()
2. The rows that get their updateDate and version columns modified

Users need to understand that:
- softDelete() only affects rows where deletedAt IS NULL
- restore() only affects rows where deletedAt IS NOT NULL

## Fix Focus Areas
- docs/docs/query-builder/4-delete-query-builder.md[19-55]
- docs/docs/working-with-entity-manager/6-repository-api.md[267-279]

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



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

Grey Divider

Previous review results

Review updated until commit 6eb9c26

Results up to commit 31cc389


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

Grey Divider
Remediation recommended
1. Missing issue reference in test comment 📘 Rule violation ✧ Quality
Description
• The new test cases validate the fix for issue #10389 but lack a comment referencing the issue
  number.
• The PR description explicitly states 'Fixes #10389', and the compliance checklist requires issue
  references in test comments when applicable.
• Other functional tests in the codebase include issue references (e.g., 'For github issue #6264',
  'Github issue #5321') to maintain traceability.
Code

test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[326]

+    it("should only soft delete rows that are not soft deleted previously", () =>
Evidence
The compliance rule requires issue references in test comments when applicable. The PR description
explicitly mentions 'Fixes #10389', and the new tests directly validate this fix. Other functional
tests in the codebase follow this pattern by including issue references in comments.

Rule 3: Prefer functional tests over per-issue tests
test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[326-326]

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 cases validate the fix for issue #10389 but lack a comment referencing the issue number, which is required by the compliance checklist when tests are added for issue fixes.

## Issue Context
The PR description explicitly states 'Fixes #10389'. The compliance rule 'Prefer functional tests over per-issue tests' requires that issue fixes add or update tests in test/functional with an issue reference in the test comment when applicable. Other functional tests in the codebase follow this pattern.

## Fix Focus Areas
- test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[326-326]
- test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[374-374]
- test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[436-436]

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


Results up to commit ea3285c


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

Grey Divider
Action required
✅ 1. Incorrect column reference in soft-delete condition 🐞 Bug ✓ Correctness
Suggestion Impact:The commit directly implements the suggested fix by replacing propertyName with databaseName and adding proper escaping using this.escape(). The implementation also removes the getWhereCondition() wrapper, directly assigning the condition string instead.

code diff:

-            condition: this.getWhereCondition(
-                `${
-                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                        ?.propertyName
-                } IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Description
• The new WHERE condition uses propertyName instead of databaseName, which will cause SQL errors
  when property names differ from database column names (e.g., deletedAt property mapped to
  deleted_at column)
• The column name is not escaped using this.escape(), violating the framework's consistent pattern
  of escaping all column identifiers to handle reserved SQL keywords
• The condition bypasses replacePropertyNames() transformation that converts property names to
  database column names throughout the codebase
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R497-503]

+            condition: this.getWhereCondition(
+                `${metadata.deleteDateColumn.propertyName} IS ${
+                    this.expressionMap.queryType === "soft-delete"
+                        ? "NULL"
+                        : "NOT NULL"
+                }`,
+            ),
Evidence
The code uses metadata.deleteDateColumn.propertyName directly in SQL without conversion or
escaping. This violates established patterns in the same file and base class. Line 462 shows the
correct approach using databaseName with escaping for the UPDATE clause. Line 868 in
QueryBuilder.ts shows the standard pattern of using replacePropertyNames() for property-to-column
conversion. The new code at lines 497-503 bypasses both mechanisms, creating SQL with TypeScript
property names instead of database column names.

src/query-builder/SoftDeleteQueryBuilder.ts[462-464]
src/query-builder/QueryBuilder.ts[862-869]
src/query-builder/SoftDeleteQueryBuilder.ts[497-503]

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 soft-delete WHERE condition incorrectly uses the TypeScript property name instead of the database column name, and doesn't escape the column identifier. This causes SQL errors when property names differ from database column names.

## Issue Context
- Property names are TypeScript entity property names (e.g., `deletedAt`)
- Database names are actual SQL column names (e.g., `deleted_at`)
- The framework consistently uses `databaseName` with `this.escape()` for SQL generation
- The `replacePropertyNames()` method handles property-to-column conversion but is bypassed here

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[497-503]

Replace the current implementation with:
```typescript
const column = this.escape(metadata.deleteDateColumn.databaseName)
this.expressionMap.wheres.push({
   type: "and",
   condition: this.getWhereCondition(
       `${column} IS ${
           this.expressionMap.queryType === "soft-delete"
               ? "NULL"
               : "NOT NULL"
       }`,
   ),
})
```

This matches the pattern used at line 462 for the UPDATE clause and ensures proper column name resolution and escaping.

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



Remediation recommended
✅ 2. Tests added to github-issues, not functional 📘 Rule violation ✓ Correctness
Suggestion Impact:The commit directly implements the suggestion by moving all three test cases from test/github-issues/10389/issue-10389.test.ts to test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts. The github-issues test file is effectively deleted (reduced to empty), and the tests are added to the functional test suite with minor adaptations (e.g., removing hardcoded IDs and using auto-generated IDs instead).

code diff:

# File: test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts
@@ -13,6 +13,7 @@
 import { UserWithoutDeleteDate } from "./entity/UserWithoutDeleteDate"
 import { Photo } from "./entity/Photo"
 import { DriverUtils } from "../../../../src/driver/DriverUtils"
+import { scheduler } from "node:timers/promises"
 
 describe("query builder > soft-delete", () => {
     let connections: DataSource[]
@@ -321,5 +322,171 @@
                 expect(usersWithSoftDelete[1].picture.deletedAt).to.equal(null)
             }),
         ))
+
+    it("should only soft delete rows that are not soft deleted previously", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                const manager = connection.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { name: "Hassan", company: "test1" },
+                    { name: "Nav", company: "test1" },
+                ]
+                const batch1Users = batch1UsersData.map(({ name, company }) => {
+                    const user = new User()
+                    user.name = name
+                    user.company = company
+                    return user
+                })
+                await manager.save(batch1Users)
+
+                // soft delete users with company test1
+                const del1 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users with the same company test1
+                const batch2UsersData = [
+                    { name: "Omer", company: "test1" },
+                    { name: "Daniyal", company: "test1" },
+                    { name: "Salman", company: "test1" },
+                    { name: "Shahzaib", company: "test1" },
+                ]
+                const batch2Users = batch2UsersData.map(({ name, company }) => {
+                    const user = new User()
+                    user.name = name
+                    user.company = company
+                    return user
+                })
+                await manager.save(batch2Users)
+
+                // soft delete users again with company test1
+                const del2 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                // now affected rows should be equal to 4 and not 6, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+            }),
+        ))
+
+    it("should correctly handle OR conditions in softDelete and not update already deleted rows", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                const manager = connection.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { name: "User 10", company: "comp1" },
+                    { name: "User 11", company: "comp1" },
+                ]
+                const batch1Users = batch1UsersData.map((data) => {
+                    const user = new User()
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch1Users)
+
+                const ids1 = batch1Users.map((u) => u.id)
+
+                // soft delete users with ID 10 OR 11
+                const del1 = await manager.softDelete(
+                    User,
+                    ids1.map((id) => ({ id })),
+                )
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users
+                const batch2UsersData = [
+                    { name: "User 12", company: "comp1" },
+                    { name: "User 13", company: "comp1" },
+                ]
+                const batch2Users = batch2UsersData.map((data) => {
+                    const user = new User()
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch2Users)
+
+                const ids2 = batch2Users.map((u) => u.id)
+
+                // soft delete users again with ID 10 OR 11 OR 12 OR 13
+                const del2 = await manager.softDelete(
+                    User,
+                    [...ids1, ...ids2].map((id) => ({ id })),
+                )
+
+                // now affected rows should be equal to 2 (batch2) and not 4, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+
+                const softDeletedUsers = await manager.find(User, {
+                    where: [...ids1, ...ids2].map((id) => ({ id })),
+                    withDeleted: true,
+                })
+                expect(softDeletedUsers.length).to.be.eql(4)
+                softDeletedUsers.forEach((user) => {
+                    expect(user.deletedAt).to.be.instanceOf(Date)
+                })
+            }),
+        ))
+
+    it("should only restore rows that are soft deleted previously", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                const manager = connection.manager
+
+                // create test users
+                const user1 = new User()
+                user1.name = "User 1"
+                user1.company = "comp1"
+
+                const user2 = new User()
+                user2.name = "User 2"
+                user2.company = "comp1"
+
+                await manager.save([user1, user2])
+
+                // soft delete user 1
+                await manager.softDelete(User, { id: user1.id })
+
+                // user1 is now deleted, user2 is NOT.
+                // Both have company "comp1".
+
+                // Get current state of user 2
+                const user2Before = await manager.findOneBy(User, {
+                    id: user2.id,
+                })
+                expect(user2Before).to.exist
+                const updatedAtBefore = user2Before!.updatedAt
+                const versionBefore = user2Before!.version
+
+                // wait a bit to ensure CURRENT_TIMESTAMP will be different if updated
+                await scheduler.wait(1000)
+
+                // restore users with company comp1
+                const restoreResult = await manager.restore(User, {
+                    company: "comp1",
+                })
+
+                // only user1 should be restored
+                expect(restoreResult.affected).to.be.eql(1)
+
+                const user1After = await manager.findOneBy(User, {
+                    id: user1.id,
+                })
+                expect(user1After!.deletedAt).to.be.null
+
+                const user2After = await manager.findOneBy(User, {
+                    id: user2.id,
+                })
+                expect(user2After!.deletedAt).to.be.null
+                // updateDate and version should NOT have changed for user 2
+                expect(user2After!.updatedAt).to.be.eql(updatedAtBefore)
+                expect(user2After!.version).to.be.eql(versionBefore)
+            }),
+        ))
 })

# File: test/github-issues/10389/issue-10389.test.ts
@@ -1,141 +1 @@
-import "reflect-metadata"
-import {
-    createTestingConnections,
-    closeTestingConnections,
-    reloadTestingDatabases,
-} from "../../utils/test-utils"
-import { DataSource } from "../../../src/data-source/DataSource"
-import { expect } from "chai"
-import { User } from "./entity/User"
 
-describe("github issues > #10389 softDelete should not update already deleted rows", () => {
-    let dataSources: DataSource[]
-    before(
-        async () =>
-            (dataSources = await createTestingConnections({
-                entities: [__dirname + "/entity/*{.js,.ts}"],
-                schemaCreate: true,
-                dropSchema: true,
-            })),
-    )
-    beforeEach(() => reloadTestingDatabases(dataSources))
-    after(() => closeTestingConnections(dataSources))
-
-    it("should only soft delete rows that are not soft deleted previously", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                // tests go here
-                const manager = dataSource.manager
-
-                // create test users
-                const batch1UsersData = [
-                    { name: "Hassan", company: "test1" },
-                    { name: "Nav", company: "test1" },
-                ]
-                const batch1Users = batch1UsersData.map(
-                    ({ name, company }, idx) => {
-                        const user = new User()
-                        user.id = idx + 1
-                        user.name = name
-                        user.company = company
-                        return user
-                    },
-                )
-                await manager.save(batch1Users)
-
-                // soft delete users with company test1
-                const del1 = await manager.softDelete(User, {
-                    company: "test1",
-                })
-                expect(del1.affected).to.be.eql(2)
-
-                // create more users with the same company test1
-                const batch2UsersData = [
-                    { name: "Omer", company: "test1" },
-                    { name: "Daniyal", company: "test1" },
-                    { name: "Salman", company: "test1" },
-                    { name: "Shahzaib", company: "test1" },
-                ]
-                const batch2Users = batch2UsersData.map(
-                    ({ name, company }, idx) => {
-                        const user = new User()
-                        user.id = idx + 3
-                        user.name = name
-                        user.company = company
-                        return user
-                    },
-                )
-                await manager.save(batch2Users)
-
-                // soft delete users again with company test1
-                const del2 = await manager.softDelete(User, {
-                    company: "test1",
-                })
-                // now affected rows should be equal to 4 and not 6, since 2 were already soft deleted before
-                expect(del2.affected).to.be.eql(batch2Users.length)
-            }),
-        ))
-
-    it("should correctly handle OR conditions in softDelete and not update already deleted rows", () =>
-        Promise.all(
-            dataSources.map(async (dataSource) => {
-                const manager = dataSource.manager
-
-                // create test users
-                const batch1UsersData = [
-                    { id: 10, name: "User 10", company: "comp1" },
-                    { id: 11, name: "User 11", company: "comp1" },
-                ]
-                const batch1Users = batch1UsersData.map((data) => {
-                    const user = new User()
-                    user.id = data.id
-                    user.name = data.name
-                    user.company = data.company
-                    return user
-                })
-                await manager.save(batch1Users)
-
-                // soft delete users with ID 10 OR 11
-                const del1 = await manager.softDelete(User, [
-                    { id: 10 },
-                    { id: 11 },
-                ])
-                expect(del1.affected).to.be.eql(2)
-
-                // create more users
-                const batch2UsersData = [
-                    { id: 12, name: "User 12", company: "comp1" },
-                    { id: 13, name: "User 13", company: "comp1" },
-                ]
-                const batch2Users = batch2UsersData.map((data) => {
-                    const user = new User()
-                    user.id = data.id
-                    user.name = data.name
-                    user.company = data.company
-                    return user
-                })
-                await manager.save(batch2Users)
-
-                // soft delete users again with ID 10 OR 11 OR 12 OR 13
-                const del2 = await manager.softDelete(User, [
-                    { id: 10 },
-                    { id: 11 },
-                    { id: 12 },
-                    { id: 13 },
-                ])
-
-                // now affected rows should be equal to 2 (batch2) and not 4, since 2 were already soft deleted before
-                expect(del2.affected).to.be.eql(batch2Users.length)
-
-                const softDeletedUsers = await manager.find(User, {
-                    where: [{ id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }],
-                    withDeleted: true,
-                })
-                expect(softDeletedUsers.length).to.be.eql(4)
-                softDeletedUsers.forEach((user) => {
-                    expect(user.deletedAt).to.be.instanceOf(Date)
-                })
-            }),
-        ))
-})
-

Description
• The PR adds tests exclusively under test/github-issues/10389/ instead of adding or updating
  tests in test/functional/query-builder/soft-delete/.
• Compliance rule 3 requires issue fixes to stay in the functional test suite with an issue
  reference in comments when applicable.
• The existing functional test suite at
  test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts does not cover the
  redundant update scenario, making this a good candidate for functional test addition.
Code

test/github-issues/10389/issue-10389.test.ts[R1-193]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { DataSource } from "../../../src/data-source/DataSource"
+import { expect } from "chai"
+import { User } from "./entity/User"
+import { scheduler } from "node:timers/promises"
+
+describe("github issues > #10389 softDelete should not update already deleted rows", () => {
+    let dataSources: DataSource[]
+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                entities: [__dirname + "/entity/*{.js,.ts}"],
+                schemaCreate: true,
+                dropSchema: true,
+            })),
+    )
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("should only soft delete rows that are not soft deleted previously", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                // tests go here
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { name: "Hassan", company: "test1" },
+                    { name: "Nav", company: "test1" },
+                ]
+                const batch1Users = batch1UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 1
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch1Users)
+
+                // soft delete users with company test1
+                const del1 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users with the same company test1
+                const batch2UsersData = [
+                    { name: "Omer", company: "test1" },
+                    { name: "Daniyal", company: "test1" },
+                    { name: "Salman", company: "test1" },
+                    { name: "Shahzaib", company: "test1" },
+                ]
+                const batch2Users = batch2UsersData.map(
+                    ({ name, company }, idx) => {
+                        const user = new User()
+                        user.id = idx + 3
+                        user.name = name
+                        user.company = company
+                        return user
+                    },
+                )
+                await manager.save(batch2Users)
+
+                // soft delete users again with company test1
+                const del2 = await manager.softDelete(User, {
+                    company: "test1",
+                })
+                // now affected rows should be equal to 4 and not 6, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+            }),
+        ))
+
+    it("should correctly handle OR conditions in softDelete and not update already deleted rows", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const manager = dataSource.manager
+
+                // create test users
+                const batch1UsersData = [
+                    { id: 10, name: "User 10", company: "comp1" },
+                    { id: 11, name: "User 11", company: "comp1" },
+                ]
+                const batch1Users = batch1UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch1Users)
+
+                // soft delete users with ID 10 OR 11
+                const del1 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                ])
+                expect(del1.affected).to.be.eql(2)
+
+                // create more users
+                const batch2UsersData = [
+                    { id: 12, name: "User 12", company: "comp1" },
+                    { id: 13, name: "User 13", company: "comp1" },
+                ]
+                const batch2Users = batch2UsersData.map((data) => {
+                    const user = new User()
+                    user.id = data.id
+                    user.name = data.name
+                    user.company = data.company
+                    return user
+                })
+                await manager.save(batch2Users)
+
+                // soft delete users again with ID 10 OR 11 OR 12 OR 13
+                const del2 = await manager.softDelete(User, [
+                    { id: 10 },
+                    { id: 11 },
+                    { id: 12 },
+                    { id: 13 },
+                ])
+
+                // now affected rows should be equal to 2 (batch2) and not 4, since 2 were already soft deleted before
+                expect(del2.affected).to.be.eql(batch2Users.length)
+
+                const softDeletedUsers = await manager.find(User, {
+                    where: [{ id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }],
+                    withDeleted: true,
+                })
+                expect(softDeletedUsers.length).to.be.eql(4)
+                softDeletedUsers.forEach((user) => {
+                    expect(user.deletedAt).to.be.instanceOf(Date)
+                })
+            }),
+        ))
+
+    it("should only restore rows that are soft deleted previously", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const manager = dataSource.manager
+
+                // create test users
+                const user1 = new User()
+                user1.id = 1
+                user1.name = "User 1"
+                user1.company = "comp1"
+
+                const user2 = new User()
+                user2.id = 2
+                user2.name = "User 2"
+                user2.company = "comp1"
+
+                await manager.save([user1, user2])
+
+                // soft delete user 1
+                await manager.softDelete(User, { id: 1 })
+
+                // user1 is now deleted, user2 is NOT.
+                // Both have company "comp1".
+
+                // Get current state of user 2
+                const user2Before = await manager.findOneBy(User, { id: 2 })
+                expect(user2Before).to.exist
+                const updatedAtBefore = user2Before!.updatedAt
+                const versionBefore = user2Before!.version
+
+                // wait a bit to ensure CURRENT_TIMESTAMP will be different if updated
+                await scheduler.wait(1000)
+
+                // restore users with company comp1
+                const restoreResult = await manager.restore(User, {
+                    company: "comp1",
+                })
+
+                // only user1 should be restored
+                expect(restoreResult.affected).to.be.eql(1)
+
+                const user1After = await manager.findOneBy(User, { id: 1 })
+                expect(user1After!.deletedAt).to.be.null
+
+                const user2After = await manager.findOneBy(User, { id: 2 })
+                expect(user2After!.deletedAt).to.be.null
+                // updateDate and version should NOT have changed for user 2
+                expect(user2After!.updatedAt).to.be.eql(updatedAtBefore)
+                expect(user2After!.version).to.be.eql(versionBefore)
+            }),
+        ))
+})
Evidence
The compliance checklist item 3 explicitly states that issue fixes should add or update tests in
test/functional with an issue reference in the test comment when applicable. The PR only adds tests
under test/github-issues/10389/ without adding corresponding tests to the functional suite. The
existing functional test at
test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts does not cover the
scenario of preventing redundant updates on already soft-deleted rows.

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

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 for preventing redundant updates on soft-deleted rows should be added to the functional test suite instead of only existing in test/github-issues.

## Issue Context
Per the project's compliance rule 3, issue fixes should add or update tests in test/functional with an issue reference in the test comment when applicable. The current implementation only adds tests under test/github-issues/10389/ without corresponding functional tests.

## Fix Focus Areas
- test/functional/query-builder/soft-delete/query-builder-soft-delete.test.ts[324-324]
- test/github-issues/10389/issue-10389.test.ts[25-193]

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


Results up to commit 3b0d2ab


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

Grey Divider
Action required
1. WHERE condition added during SQL generation 🐞 Bug ✓ Correctness
Description
• The new WHERE condition checking deleteDateColumn is added inside createUpdateExpression(), which
  is called during SQL generation (getQuery() or execute())
• This mutates the shared expressionMap.wheres array during query generation, not during query
  building
• If the query builder is reused or getQuery() is called multiple times, the condition will be added
  repeatedly, resulting in duplicate WHERE clauses
• This violates the principle that query generation should be idempotent and side-effect-free
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R495-504]

+        this.expressionMap.wheres.push({
+            type: "and",
+            condition: this.getWhereCondition(
+                `${metadata.deleteDateColumn.propertyName} IS ${
+                    this.expressionMap.queryType === "soft-delete"
+                        ? "NULL"
+                        : "NOT NULL"
+                }`,
+            ),
+        })
Evidence
The code shows that the WHERE condition is pushed to expressionMap.wheres inside
createUpdateExpression() method. This method is called from getQuery() (line 48), which is a query
generation method that should be side-effect-free. The QueryBuilder pattern in TypeORM allows
calling getQuery() multiple times on the same builder instance, and each call should produce the
same SQL. By mutating the wheres array during generation, subsequent calls will add duplicate
conditions. The where() method (lines 194-201) properly resets the wheres array before adding
conditions, showing that WHERE clause setup should happen during query building, not generation.

src/query-builder/SoftDeleteQueryBuilder.ts[494-504]
src/query-builder/SoftDeleteQueryBuilder.ts[47-52]
src/query-builder/SoftDeleteQueryBuilder.ts[193-201]

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 WHERE condition for filtering already soft-deleted/restored rows is currently added inside `createUpdateExpression()`, which is called during SQL generation. This causes the condition to be added every time `getQuery()` or `execute()` is called, leading to duplicate WHERE clauses if the query builder is reused.

## Issue Context
The current implementation adds the WHERE condition at:
- src/query-builder/SoftDeleteQueryBuilder.ts[494-504]

The condition is added during SQL generation when `createUpdateExpression()` is called from:
- src/query-builder/SoftDeleteQueryBuilder.ts[48] (in getQuery())
- src/query-builder/SoftDeleteQueryBuilder.ts[105] (in execute() via getQueryAndParameters())

## Fix Focus Areas
Move the WHERE condition addition to where the query type is set:
- src/query-builder/QueryBuilder.ts[278-284] (softDelete() method)
- src/query-builder/QueryBuilder.ts[286-292] (restore() method)

Remove the WHERE condition addition from:
- src/query-builder/SoftDeleteQueryBuilder.ts[494-504]

The fix should add the WHERE condition immediately after setting the query type, similar to how other query builders handle their default conditions.

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


Results up to commit 60eb587


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

Grey Divider
Action required
✅ 1. Incorrect column reference in SQL WHERE 🐞 Bug ✓ Correctness
Suggestion Impact:The commit directly implements the suggestion by replacing `propertyName` with `databaseName` in the WHERE condition construction. The code now uses `metadata.deleteDateColumn.databaseName` with proper escaping via `this.escape()`, which aligns with the established pattern in the file. The commit also removed the unnecessary `getWhereCondition()` wrapper and directly constructs the condition string.

code diff:

-            condition: this.getWhereCondition(
-                `${
-                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                        ?.propertyName
-                } IS ${
-                    this.expressionMap.queryType === "soft-delete"
-                        ? "NULL"
-                        : "NOT NULL"
-                }`,
-            ),
+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Description
• The code uses propertyName (TypeScript property like 'deletedAt') instead of databaseName
  (actual database column like 'deleted_at') when constructing the SQL WHERE condition
• This violates the established pattern used throughout the same file where databaseName is
  consistently used for SQL construction (lines 462, 468, 479, 481, 486)
• While replacePropertyNamesForTheWholeQuery() may convert it later, this creates inconsistency
  and maintenance burden
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R499-500]

+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
Evidence
The established pattern in the same file consistently uses metadata.deleteDateColumn.databaseName
with proper escaping for all SQL column references. The new code breaks this pattern by using
propertyName instead.

src/query-builder/SoftDeleteQueryBuilder.ts[462-463]
src/query-builder/SoftDeleteQueryBuilder.ts[468-469]
src/query-builder/SoftDeleteQueryBuilder.ts[479-482]

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 WHERE condition construction uses `deleteDateColumn?.propertyName` instead of `deleteDateColumn.databaseName`, which is inconsistent with the established pattern in the same file.

## Issue Context
In TypeORM, `propertyName` refers to the TypeScript/JavaScript property name (e.g., 'deletedAt'), while `databaseName` refers to the actual database column name (e.g., 'deleted_at'). The file consistently uses `databaseName` for SQL construction.

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[499-500]

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


✅ 2. Missing escape() for SQL identifier 🐞 Bug ✓ Correctness
Suggestion Impact:The commit directly addresses the suggestion by adding the escape() method to properly quote the column identifier. The implementation wraps the column name (metadata.deleteDateColumn.databaseName) with this.escape(), and also simplifies the code by removing the getWhereCondition() wrapper and using databaseName instead of propertyName.

code diff:

+            condition: `${this.escape(
+                metadata.deleteDateColumn.databaseName,
+            )} IS ${
+                this.expressionMap.queryType === "soft-delete"
+                    ? "NULL"
+                    : "NOT NULL"
+            }`,

Description
• The column name in the WHERE condition is not escaped using the escape() method
• The escape() method handles database-specific identifier quoting (backticks for MySQL, double
  quotes for PostgreSQL, etc.)
• Without proper escaping, the SQL could fail with syntax errors in databases that require quoted
  identifiers or when column names contain reserved keywords
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R497-506]

+            condition: this.getWhereCondition(
+                `${
+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
+                } IS ${
+                    this.expressionMap.queryType === "soft-delete"
+                        ? "NULL"
+                        : "NOT NULL"
+                }`,
+            ),
Evidence
All column references in SQL construction within this file use the this.escape() method to
properly quote identifiers. The new WHERE condition construction omits this critical step, which
could cause SQL syntax errors.

src/query-builder/SoftDeleteQueryBuilder.ts[462-463]
src/query-builder/SoftDeleteQueryBuilder.ts[468-469]
src/query-builder/SoftDeleteQueryBuilder.ts[486-487]

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 WHERE condition construction does not use the `escape()` method to quote the column identifier, which could cause SQL syntax errors in certain database configurations.

## Issue Context
The `escape()` method in TypeORM serves two purposes:
1. Ensures database-specific identifier quoting (e.g., backticks for MySQL, double quotes for PostgreSQL)
2. Protects against SQL injection and handles reserved keywords

All other column references in this file use `this.escape()` consistently.

## Fix Focus Areas
- src/query-builder/SoftDeleteQueryBuilder.ts[497-506]

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



Remediation recommended
✅ 3. Unnecessary optional chaining operator 🐞 Bug ✓ Correctness
Suggestion Impact:The commit removed the optional chaining operator (?.) from deleteDateColumn.propertyName access and also simplified the code by using a metadata variable directly instead of the full expression path.

code diff:

-                `${
-                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
-                        ?.propertyName
-                } IS ${
+                `${metadata.deleteDateColumn.propertyName} IS ${

Description
• The code uses optional chaining deleteDateColumn?.propertyName which is unnecessary because line
  452-454 already validates that deleteDateColumn exists
• This violates the pattern established at lines 462 and 468 where deleteDateColumn is accessed
  without optional chaining
• The unnecessary defensive coding could mask bugs and confuse future maintainers about the actual
  guarantees
Code

src/query-builder/SoftDeleteQueryBuilder.ts[R499-500]

+                    this.expressionMap.mainAlias!.metadata.deleteDateColumn
+                        ?.propertyName
Evidence
The code at lines 452-454 throws MissingDeleteDateColumnError if deleteDateColumn is null/undefined,
guaranteeing it exists at line 499. The optional chaining operator is inconsistent with how the same
property is accessed elsewhere in the method.

src/query-builder/SoftDeleteQueryBuilder.ts[452-454]
src/query-builder/SoftDeleteQueryBuilder.ts[462-463]
src/query-builder/SoftDeleteQueryBuilder.ts[468-469]

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 code uses optional chaining `deleteDateColumn?.propertyName` even though deleteDateColumn is guaranteed to exist due to the null check at lines 452-454.

## Issue Context
The null check at the beginning of the method ensures deleteDateColumn is defined. Using optional chaining here is inconsistent with the pattern used at lines 462 and 468 where the same propert...

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

Copy link
Copy Markdown

Persistent review updated to latest commit 3b0d2ab

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

Copy link
Copy Markdown

Persistent review updated to latest commit ea3285c

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

Copy link
Copy Markdown

Persistent review updated to latest commit 31cc389

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

Copy link
Copy Markdown

Persistent review updated to latest commit 6eb9c26

@gioboa
gioboa merged commit 60b10c8 into typeorm:master Jan 18, 2026
69 of 71 checks passed
@github-project-automation github-project-automation Bot moved this from Proposed to Done in TypeORM Roadmap Jan 18, 2026
@shoaibmarif

Copy link
Copy Markdown

@hassanmehdi98 highly appreciated ✨

kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

softDelete should not update already deleted rows

8 participants