Skip to content

feat: add returning option to update/upsert operations - #11782

Merged
gioboa merged 16 commits into
v0.3from
feature/returning-selection
Jan 11, 2026
Merged

gioboa merged 16 commits into
v0.3from
feature/returning-selection

Conversation

@naorpeled

@naorpeled naorpeled commented Nov 19, 2025 •

Copy link
Copy Markdown
Member

Summary

  • allow repository/entity manager update APIs to accept returning options when supported
  • wire returning option through upsert/update/updateAll and expose typings
  • add coverage and docs for the new feature

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 19, 2025 •

Copy link
Copy Markdown

Deploying typeorm with  Cloudflare Pages  Cloudflare Pages

Latest commit: dcb5d51
Status: ✅  Deploy successful!
Preview URL: https://f56da34c.typeorm.pages.dev
Branch Preview URL: https://feature-returning-selection.typeorm.pages.dev

View logs

@naorpeled
naorpeled marked this pull request as draft November 19, 2025 20:14
coderabbitai[bot]

This comment was marked as resolved.

@pkg-pr-new

pkg-pr-new Bot commented Nov 21, 2025 •

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

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

commit: dcb5d51

Comment thread src/index.ts Resolved
@naorpeled naorpeled linked an issue Nov 21, 2025 that may be closed by this pull request
1 of 18 tasks
@typeorm typeorm deleted a comment from coderabbitai Bot Nov 29, 2025
@coveralls

coveralls commented Dec 13, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.76% (-0.006%) from 80.766%
when pulling dcb5d51 on feature/returning-selection
into d21a08c on v0.3.

@naorpeled
naorpeled marked this pull request as ready for review December 13, 2025 22:23
Copilot AI review requested due to automatic review settings December 13, 2025 22:23
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Code Duplication

The update method contains duplicated code blocks for handling the returning option in both the primitive criteria and non-primitive criteria branches. This duplication could be refactored by extracting the common logic after the conditional block.

    const qb = this.createQueryBuilder()
        .update(target)
        .set(partialEntity)
        .whereInIds(criteria)

    if (options?.returning !== undefined) {
        qb.returning(options.returning)
    }

    return qb.execute()
} else {
    const qb = this.createQueryBuilder()
        .update(target)
        .set(partialEntity)
        .where(criteria)

    if (options?.returning !== undefined) {
        qb.returning(options.returning)
    }

    return qb.execute()
}
Unused Parameter

The isReturningSqlSupported method now accepts a returningType parameter but doesn't use it in the implementation. This could indicate incomplete implementation or that the parameter should be used to determine support for different types of RETURNING clauses (insert vs update).

isReturningSqlSupported(returningType: ReturningType): boolean {
    if (
        this.options.options &&
        this.options.options.disableOutputReturning
    ) {
        return false
Test Coverage Gap

The test suite only covers update and upsert operations but doesn't test the updateAll method which also received the new returning option. Additionally, tests skip drivers that don't support returning but don't verify the behavior when returning is specified on unsupported drivers.

it("allows specifying RETURNING via repository.update options", () =>
    Promise.all(
        connections.map(async (connection) => {
            if (!connection.driver.isReturningSqlSupported("update")) {
                return
            }

            const repo = connection.getRepository(User)
            const created = await repo.save({ name: "before" })

            const result = await repo.update(
                created.id,
                { name: "after" },
                { returning: ["id", "name"] },
            )

            expect(result.raw).to.be.an("array")
            expect(result.raw[0]).to.include({
                id: created.id,
                name: "after",
            })
        }),
    ))

it("allows specifying RETURNING via repository.upsert options", () =>
    Promise.all(
        connections.map(async (connection) => {
            if (!connection.driver.isReturningSqlSupported("insert")) {
                return
            }

            const repo = connection.getRepository(User)
            const created = await repo.save({ name: "seed" })

            const result = await repo.upsert(
                { id: created.id, name: "seed-updated" },
                {
                    conflictPaths: ["id"],
                    returning: ["id", "name"],
                },
            )

            expect(result.raw).to.be.an("array")
            expect(result.raw[0]).to.include({
                id: created.id,
                name: "seed-updated",
            })
        }),
    ))

@naorpeled naorpeled changed the title feat: configurable returning on updates feat: add returning option to update/upsert operations Dec 13, 2025
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to dcb5d51

CategorySuggestion                                                                                                                                    Impact
General
Prefix unused parameter with underscore

Prefix the unused returningType parameter in isReturningSqlSupported with an
underscore for consistency and to signal it is intentionally unused.

src/driver/sqlserver/SqlServerDriver.ts [918-926]

-isReturningSqlSupported(returningType: ReturningType): boolean {
+isReturningSqlSupported(_returningType: ReturningType): boolean {
     if (
         this.options.options &&
         this.options.options.disableOutputReturning
     ) {
         return false
     }
     return true
 }
  • Apply / Chat
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies an unused parameter and proposes prefixing it with an underscore, which improves consistency with other driver implementations modified in this PR.

Low
  • More

Previous suggestions

Suggestions up to commit 028c519
CategorySuggestion                                                                                                                                    Impact
General
Unused parameter in method signature

The returningType parameter in isReturningSqlSupported is unused; prefix it with
an underscore to signify this, and consider a more robust implementation that
validates the specific returning type.

src/driver/sqlserver/SqlServerDriver.ts [918-926]

-isReturningSqlSupported(returningType: ReturningType): boolean {
+isReturningSqlSupported(_returningType: ReturningType): boolean {
     if (
         this.options.options &&
         this.options.options.disableOutputReturning
     ) {
         return false
     }
     return true
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies that the returningType parameter is unused, which is a minor code quality issue. The proposed change to add an underscore aligns with common coding conventions for unused parameters.

Low
Suggestions up to commit eec0d37
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate driver RETURNING support

Add a check to verify if the database driver supports the RETURNING clause for
insert operations before applying the returning option in the upsert method.

src/entity-manager/EntityManager.ts [744-767]

 const qb = this.createQueryBuilder()
     .insert()
     .into(target)
     .values(entities)
     .orUpdate(
         [...conflictColumns, ...overwriteColumns].map(
             (col) => col.databaseName,
         ),
         conflictColumns.map((col) => col.databaseName),
         {
             skipUpdateIfNoValuesChanged:
                 options.skipUpdateIfNoValuesChanged,
             indexPredicate: options.indexPredicate,
             upsertType:
                 options.upsertType ||
                 this.connection.driver.supportedUpsertTypes[0],
         },
     )
 
 if (options.returning !== undefined) {
+    if (!this.connection.driver.isReturningSqlSupported("insert")) {
+        throw new TypeORMError(
+            `RETURNING clause is not supported by ${this.connection.driver.options.type} driver`
+        )
+    }
     qb.returning(options.returning)
 }
 
 return qb.execute()
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that using the returning option without checking for driver support could lead to runtime errors. Adding a guard with isReturningSqlSupported improves robustness and provides clearer error messages.

Medium
Suggestions up to commit 7d33e73
CategorySuggestion                                                                                                                                    Impact
General
Unused parameter in method signature

Prefix the unused returningType parameter in isReturningSqlSupported with an
underscore to indicate it is intentionally not used.

src/driver/sqlserver/SqlServerDriver.ts [918-926]

-isReturningSqlSupported(returningType: ReturningType): boolean {
+isReturningSqlSupported(_returningType: ReturningType): boolean {
     if (
         this.options.options &&
         this.options.options.disableOutputReturning
     ) {
         return false
     }
     return true
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies an unused parameter returningType. While the proposed change to add an underscore is a valid style improvement for maintainability, it doesn't alter functionality and has a minor impact.

Low
Suggestions up to commit d03f7f3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate driver RETURNING support

Add a validation check to ensure the database driver supports the RETURNING
clause for the specific operation before applying it, throwing an error if
unsupported.

src/entity-manager/EntityManager.ts [807-809]

 if (options?.returning !== undefined) {
+    if (!this.connection.driver.isReturningSqlSupported("update")) {
+        throw new TypeORMError(
+            `RETURNING clause is not supported by ${this.connection.driver.options.type} driver for UPDATE operations`
+        )
+    }
     qb.returning(options.returning)
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a missing validation check. Adding a check using this.connection.driver.isReturningSqlSupported() before attempting to use a RETURNING clause would prevent runtime SQL errors on unsupported drivers and provide a better developer experience.

Medium
General
Unused parameter in method signature

The returningType parameter in the isReturningSqlSupported method is unused.
Utilize this parameter to provide more accurate support information based on the
operation type, or remove it.

src/driver/sqlserver/SqlServerDriver.ts [918-926]

-isReturningSqlSupported(returningType: ReturningType): boolean {
+isReturningSqlSupported(_returningType: ReturningType): boolean {
     if (
         this.options.options &&
         this.options.options.disableOutputReturning
     ) {
         return false
     }
     return true
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies that the returningType parameter is unused. While using it could make the driver's capability reporting more precise, the current implementation is not incorrect, just less specific. This is a minor code quality improvement.

Low
Suggestions up to commit 0359a7b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Disable returning support for Spanner

Disable RETURNING support for the Spanner driver by returning false from
isReturningSqlSupported to prevent runtime errors, as its unique THEN RETURN
syntax is not implemented.

src/driver/spanner/SpannerDriver.ts [699-701]

 isReturningSqlSupported(_returningType: ReturningType): boolean {
-    return true
+    return false
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies that Spanner's THEN RETURN syntax is not supported by the current implementation, and enabling it would lead to runtime errors for users of that driver.

High

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR adds support for configurable RETURNING/OUTPUT clauses on repository update, updateAll, and upsert methods. Previously, these clauses could only be specified when using the query builder directly. Now developers can request returned values through a new returning option parameter when calling these higher-level repository methods.

Key changes:

  • New UpdateOptions interface with optional returning field for update and updateAll methods
  • Extended UpsertOptions interface to include optional returning field
  • Updated method signatures across Repository, BaseEntity, and EntityManager to accept these options
  • Driver interface updated to accept ReturningType parameter for better type safety

Reviewed changes

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

Show a summary per file
File Description
src/repository/UpdateOptions.ts New interface defining options for update methods, including returning clause
src/repository/UpsertOptions.ts Extended to include returning option for upsert operations
src/query-builder/ReturningOption.ts New type definition for RETURNING clause (string or string array)
src/repository/Repository.ts Updated update and updateAll signatures to accept optional UpdateOptions parameter
src/repository/BaseEntity.ts Updated static update method signature to accept optional UpdateOptions
src/entity-manager/EntityManager.ts Implementation changes to wire returning option through query builder for update, updateAll, and upsert
src/driver/sqlserver/SqlServerDriver.ts Updated isReturningSqlSupported to accept ReturningType parameter
src/driver/spanner/SpannerDriver.ts Updated isReturningSqlSupported to accept ReturningType parameter
src/driver/postgres/PostgresDriver.ts Updated isReturningSqlSupported to accept ReturningType parameter
src/driver/oracle/OracleDriver.ts Updated isReturningSqlSupported to accept ReturningType parameter
src/driver/cockroachdb/CockroachDriver.ts Updated isReturningSqlSupported to accept ReturningType parameter
src/index.ts Exports UpdateOptions as RepositoryUpdateOptions (to avoid MongoDB type conflict) and ReturningOption
docs/docs/working-with-entity-manager/6-repository-api.md Added documentation examples showing how to use returning option with update, updateAll, and upsert
test/functional/repository/returning/repository-returning.ts New test file covering update and upsert with returning options
test/functional/repository/returning/entity/User.ts Simple test entity for returning tests

@naorpeled
naorpeled changed the base branch from master to v0.3 December 19, 2025 21:25
@naorpeled
naorpeled changed the base branch from v0.3 to master December 19, 2025 21:25
@naorpeled
naorpeled changed the base branch from master to v0.3 December 19, 2025 21:30
@naorpeled
naorpeled requested review from alumni, gioboa and sgarner and removed request for alumni and gioboa January 3, 2026 22:15
@naorpeled

naorpeled commented Jan 10, 2026 •

Copy link
Copy Markdown
Member Author

@gioboa @alumni @G0maa
wdyt?🙏

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

LGTM 💪

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

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

Grey Divider

Great, No Issues Found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Qodo Logo

@G0maa
G0maa self-requested a review January 11, 2026 09:16

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

🚀

Comment on lines +146 to +151
const result = await repository.update(
1,
{ firstName: "Rizzrak" },
{ returning: ["id", "firstName"] },
)
console.log(result.raw) // [{ id: 1, firstName: "Rizzrak" }]

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.

As a stretch goal in the future, any idea how could we make this type-safe? i.e. result.id & result.firstName become defined on result.... somehow.

@gioboa
gioboa merged commit 11d9767 into v0.3 Jan 11, 2026
45 checks passed
@gioboa
gioboa deleted the feature/returning-selection branch January 11, 2026 12:49
@@ -0,0 +1,99 @@
import { expect } from "chai"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The test is not ending with .test.ts 🙈 so it's not running

gioboa pushed a commit to gioboa/typeorm that referenced this pull request Jan 13, 2026
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
ztrayner added a commit to ztrayner/typeorm that referenced this pull request Feb 2, 2026
## Summary
- allow repository/entity manager delete APIs to accept returning options when supported
- wire returning option through delete/deleteAll and expose typings
- add coverage and docs for the new feature

This follows the same pattern established in PR typeorm#11782 for update/upsert operations.

Co-authored-by: Cursor <[email protected]>
ztrayner added a commit to ztrayner/typeorm that referenced this pull request Feb 2, 2026
## Summary
- allow repository/entity manager delete APIs to accept returning options when supported
- wire returning option through delete/deleteAll and expose typings
- add coverage and docs for the new feature

This follows the same pattern established in PR typeorm#11782 for update/upsert operations.

Co-authored-by: Cursor <[email protected]>
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.

Add RETURNING option to upsert

6 participants