Skip to content

feat: support INSERT INTO ... SELECT FROM ... in QueryBuilder - #11896

Merged
gioboa merged 8 commits into
typeorm:masterfrom
Cprakhar:feat/support-insert-into-select-from
Jan 16, 2026
Merged

gioboa merged 8 commits into
typeorm:masterfrom
Cprakhar:feat/support-insert-into-select-from

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 6, 2026 •

Copy link
Copy Markdown
Collaborator

Description of change

This PR adds support for INSERT INTO ... SELECT FROM queries in QueryBuilder, addressing a common feature request for data migration and transformation tasks.

What the change does:

  • Adds a new valuesFromSelect() method to InsertQueryBuilder.ts that accepts either a SelectQueryBuilder instance or a callback function
  • Generates standard SQL INSERT INTO table (columns) SELECT ... FROM ... syntax
  • Properly merges parameters from the SELECT query into the INSERT query

Why this change is needed:

  • The INSERT INTO ... SELECT FROM pattern is essential for data migration, archiving, ETL processes, and copying/transforming data between tables
  • Previously, users had to use raw queries to achieve this functionality

How I've verified it:

  • Added functional tests covering basic usage, callback API, WHERE conditions, and JOINs
  • Tests are conducted on various database types, including PostgreSQL, MySQL, and SQLite, but excluding Spanner (a lot of work to set up locally for testing)
  • Verified SQL generation produces correct syntax

Notes:

  • Entity listeners/subscribers (@BeforeInsert, @AfterInsert) are skipped since no entity instances are created
  • The updateEntity option has no effect with valuesFromSelect()

Pull-Request Checklist

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

Fixes #8538

@pkg-pr-new

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

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

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

commit: a39e57b

@Cprakhar

This comment was marked as resolved.

@Cprakhar
Cprakhar marked this pull request as ready for review January 7, 2026 08:29
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

8538 - Partially compliant

Compliant requirements:

  • Allows InsertQueryBuilder to use SELECT queries via valuesFromSelect() method
  • Generates correct INSERT INTO ... SELECT FROM SQL syntax
  • Accepts SelectQueryBuilder instance or callback function
  • Supports multiple database drivers through standard SQL generation

Non-compliant requirements:

  • Method is named valuesFromSelect() instead of from() as suggested in the ticket
  • Does not support the alias parameter mentioned in the ticket's proposed API
  • Does not wrap the SELECT in a subquery with alias as suggested in the alternative solution

Requires further human verification:

  • Verify the generated SQL works correctly across all mentioned database drivers (aurora-data-api, cockroachdb, mongodb, oracle, sap, etc.)
  • Confirm that the direct SELECT approach (without subquery wrapping) is compatible with all target databases
  • Validate that skipping entity listeners/subscribers is acceptable behavior for this use case
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Parameter Merging

The setParameters() call at line 381 may overwrite existing parameters in the insert query builder if there are naming conflicts between the select query parameters and any previously set insert query parameters. Consider using parameter merging that preserves both sets of parameters or validates for conflicts.

this.setParameters(selectQueryBuilder.getParameters())
Missing Validation

The valuesFromSelect() method does not validate that the number of selected columns matches the number of insert columns specified. This could lead to SQL errors at runtime. Consider adding validation to ensure column count compatibility between the SELECT and INSERT statements.

valuesFromSelect(
    queryBuilderOrFactory:
        | SelectQueryBuilder<any>
        | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
): this {
    let selectQueryBuilder: SelectQueryBuilder<any>

    if (typeof queryBuilderOrFactory === "function") {
        // Create a new SelectQueryBuilder and pass it to the factory
        const subQuery = this.createQueryBuilder().select()
        selectQueryBuilder = queryBuilderOrFactory(subQuery)
    } else {
        selectQueryBuilder = queryBuilderOrFactory
    }

    // Merge parameters from the SelectQueryBuilder
    this.setParameters(selectQueryBuilder.getParameters())

    // Store the SelectQueryBuilder reference
    this.expressionMap.insertFromSelect = selectQueryBuilder

    return this
}
Silent Error Handling

The rollback error at line 268 is caught and silently ignored with an empty catch block. This could hide important error information during transaction rollback failures. Consider logging the rollback error or re-throwing it appropriately.

if (transactionStartedByUs) {
    try {
        await queryRunner.rollbackTransaction()
    } catch (rollbackError) {}
}

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to a39e57b

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate select and column count match

Add validation to ensure the number of select expressions matches the number of
target columns when creating a MERGE statement from an INSERT ... SELECT,
throwing an error if they do not match.

src/query-builder/InsertQueryBuilder.ts [1252-1289]

 if (this.expressionMap.insertFromSelect) {
-    // For MERGE source we need the SELECT's output columns to match
-    // the target column names referenced as `mergeIntoSource.<col>`.
-    // MSSQL supports providing a column list after the alias, so
-    // in that case we can keep the original SELECT. For other
-    // drivers (e.g. Oracle, SAP HANA) we clone the select and set
-    // the select aliases to the target column database names so
-    // references like `mergeIntoSource.email` resolve correctly.
     if (this.connection.driver.options.type === "mssql") {
         expression += this.expressionMap.insertFromSelect.getQuery()
     } else {
-        // Clone the SelectQueryBuilder and modify its select expressions
         const selectQb = this.expressionMap.insertFromSelect.clone()
         const targetColumns = this.getInsertedColumns()
-
-        // Clear existing selects and add new ones with proper aliases
-        selectQb.expressionMap.selects = []
-
-        // Get the original select expressions
         const originalSelects =
             this.expressionMap.insertFromSelect.expressionMap.selects
 
+        if (originalSelects.length !== targetColumns.length) {
+            throw new TypeORMError(
+                `Number of select expressions (${originalSelects.length}) must match number of target columns (${targetColumns.length})`
+            )
+        }
+
+        selectQb.expressionMap.selects = []
+
         originalSelects.forEach((select, index) => {
             const targetColumn = targetColumns[index]
-            if (targetColumn) {
-                // Add select with target column name as alias
-                selectQb.expressionMap.selects.push({
-                    selection: select.selection,
-                    aliasName: targetColumn.databaseName,
-                    virtual: select.virtual,
-                })
-            } else {
-                selectQb.expressionMap.selects.push(select)
-            }
+            selectQb.expressionMap.selects.push({
+                selection: select.selection,
+                aliasName: targetColumn.databaseName,
+                virtual: select.virtual,
+            })
         })
 
         expression += selectQb.getQuery()
     }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a missing validation that could lead to incorrect SQL generation or runtime errors, and proposes adding an explicit check to prevent this, which is a significant improvement for error handling.

Medium
General
Respect explicitly specified generated columns

Modify the logic for skipping generated columns in INSERT FROM SELECT queries to
allow insertion if the column is explicitly listed in insertColumns.

src/query-builder/InsertQueryBuilder.ts [790-799]

 if (
     column.isGenerated &&
     this.expressionMap.insertFromSelect &&
+    !this.expressionMap.insertColumns.includes(column.propertyPath) &&
     (DriverUtils.isSQLiteFamily(this.connection.driver) ||
         DriverUtils.isMySQLFamily(this.connection.driver) ||
         this.connection.driver.options.type ===
             "aurora-mysql" ||
         this.connection.driver.options.type === "oracle")
 )
     return false
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that the current logic prevents inserting into generated columns even if explicitly requested, and the proposed change correctly allows this override, improving the feature's flexibility.

Medium
Preserve existing parameters when merging

Instead of replacing all existing parameters with setParameters, merge the
parameters from the select query to avoid accidentally overwriting any
parameters set by other parts of the query.

src/query-builder/InsertQueryBuilder.ts [284-300]

 valuesFromSelect(
     queryBuilderOrFactory:
         | SelectQueryBuilder<any>
         | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
 ): this {
     let selectQueryBuilder: SelectQueryBuilder<any>
     if (typeof queryBuilderOrFactory === "function") {
         const subQuery = this.createQueryBuilder().select()
         selectQueryBuilder = queryBuilderOrFactory(subQuery)
     } else {
         selectQueryBuilder = queryBuilderOrFactory
     }
-    this.setParameters(selectQueryBuilder.getParameters())
+    const selectParams = selectQueryBuilder.getParameters()
+    Object.keys(selectParams).forEach(key => {
+        this.setParameter(key, selectParams[key])
+    })
     this.expressionMap.insertFromSelect = selectQueryBuilder
 
     return this
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that setParameters is a destructive operation and proposes a safer merge-like approach, which increases the robustness of the new valuesFromSelect method against potential edge cases.

Low
  • More

Previous suggestions

Suggestions up to commit 49f9445
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate column count mismatch

Add a validation check to ensure the number of columns in the INSERT clause
matches the number of columns in the SELECT query to prevent runtime SQL errors.

src/query-builder/InsertQueryBuilder.ts [521-522]

-if (this.expressionMap.insertFromSelect)
+if (this.expressionMap.insertFromSelect) {
+    const insertColumns = this.getInsertedColumns()
+    const selectColumns = this.expressionMap.insertFromSelect.expressionMap.selects
+    if (insertColumns.length > 0 && selectColumns.length > 0 && insertColumns.length !== selectColumns.length) {
+        throw new TypeORMError(
+            `Column count mismatch: INSERT expects ${insertColumns.length} columns but SELECT provides ${selectColumns.length} columns`
+        )
+    }
     query += ` ${this.expressionMap.insertFromSelect.getQuery()}`
+}
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a missing validation that could lead to runtime SQL errors, and proposes adding a check to provide a clearer error message to the developer, which improves usability.

Medium
Preserve existing query parameters

Instead of overwriting existing query parameters in valuesFromSelect, merge them
with the parameters from the select query to prevent accidental data loss.

src/query-builder/InsertQueryBuilder.ts [284-300]

 valuesFromSelect(
     queryBuilderOrFactory:
         | SelectQueryBuilder<any>
         | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
 ): this {
     let selectQueryBuilder: SelectQueryBuilder<any>
     if (typeof queryBuilderOrFactory === "function") {
         const subQuery = this.createQueryBuilder().select()
         selectQueryBuilder = queryBuilderOrFactory(subQuery)
     } else {
         selectQueryBuilder = queryBuilderOrFactory
     }
-    this.setParameters(selectQueryBuilder.getParameters())
+    const selectParams = selectQueryBuilder.getParameters()
+    Object.keys(selectParams).forEach(key => {
+        this.setParameter(key, selectParams[key])
+    })
     this.expressionMap.insertFromSelect = selectQueryBuilder
 
     return this
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies that setParameters overwrites all existing parameters, and the proposed change to merge them instead makes the new valuesFromSelect method more robust and predictable.

Low
General
Respect explicitly specified columns

Modify the logic to ensure that if a user explicitly includes a generated column
in an INSERT FROM SELECT query, it is not silently ignored.

src/query-builder/InsertQueryBuilder.ts [790-799]

 if (
     column.isGenerated &&
     this.expressionMap.insertFromSelect &&
+    this.expressionMap.insertColumns.length === 0 &&
     (DriverUtils.isSQLiteFamily(this.connection.driver) ||
         DriverUtils.isMySQLFamily(this.connection.driver) ||
         this.connection.driver.options.type ===
             "aurora-mysql" ||
         this.connection.driver.options.type === "oracle")
 )
     return false
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that explicitly specified generated columns might be incorrectly excluded, and proposes a change to respect the user's explicit column selection, improving the feature's consistency.

Low
Suggestions up to commit 6cad117
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate column count matches

In valuesFromSelect(), validate that the number of columns in the SELECT query
matches the number of target columns for the INSERT operation to prevent runtime
SQL errors.

src/query-builder/InsertQueryBuilder.ts [284-300]

 valuesFromSelect(
     queryBuilderOrFactory:
         | SelectQueryBuilder<any>
         | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
 ): this {
     let selectQueryBuilder: SelectQueryBuilder<any>
     if (typeof queryBuilderOrFactory === "function") {
         const subQuery = this.createQueryBuilder().select()
         selectQueryBuilder = queryBuilderOrFactory(subQuery)
     } else {
         selectQueryBuilder = queryBuilderOrFactory
     }
+    
+    // Validate column count match
+    const selectCount = selectQueryBuilder.expressionMap.selects.length
+    const targetColumns = this.getInsertedColumns()
+    if (selectCount > 0 && targetColumns.length > 0 && selectCount !== targetColumns.length) {
+        throw new TypeORMError(
+            `Column count mismatch: SELECT has ${selectCount} columns but INSERT expects ${targetColumns.length} columns`
+        )
+    }
+    
     this.setParameters(selectQueryBuilder.getParameters())
     this.expressionMap.insertFromSelect = selectQueryBuilder
 
     return this
 }
Suggestion importance[1-10]: 7

__

Why: This is a good suggestion for improving developer experience by adding early validation, which would provide a clearer error message than a generic SQL error.

Medium
Validate column count in MERGE

In createMergeIntoSourceExpression(), validate that the number of columns in the
SELECT query matches the number of target INSERT columns to prevent SQL errors
in MERGE operations.

src/query-builder/InsertQueryBuilder.ts [1248-1270]

 const selectQb = this.expressionMap.insertFromSelect.clone()
 const targetColumns = this.getInsertedColumns()
 
 // Clear existing selects and add new ones with proper aliases
 selectQb.expressionMap.selects = []
 
 // Get the original select expressions
 const originalSelects =
     this.expressionMap.insertFromSelect.expressionMap.selects
 
+if (originalSelects.length !== targetColumns.length) {
+    throw new TypeORMError(
+        `Column count mismatch in MERGE source: SELECT has ${originalSelects.length} columns but INSERT expects ${targetColumns.length} columns`
+    )
+}
+
 originalSelects.forEach((select, index) => {
     const targetColumn = targetColumns[index]
-    if (targetColumn) {
-        // Add select with target column name as alias
-        selectQb.expressionMap.selects.push({
-            selection: select.selection,
-            aliasName: targetColumn.databaseName,
-            virtual: select.virtual,
-        })
-    } else {
-        selectQb.expressionMap.selects.push(select)
-    }
+    selectQb.expressionMap.selects.push({
+        selection: select.selection,
+        aliasName: targetColumn.databaseName,
+        virtual: select.virtual,
+    })
 })
Suggestion importance[1-10]: 7

__

Why: This is a valid suggestion that improves robustness by adding a check for column count mismatch in MERGE statements with INSERT ... SELECT, preventing potential SQL errors with a clear message.

Medium
Suggestions up to commit 29a62dc
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle transaction commit failures properly

Improve transaction handling in executeInsertFromSelect by adding a try/catch
block around commitTransaction to ensure a rollback occurs if the commit fails.

src/query-builder/InsertQueryBuilder.ts [237-277]

 protected async executeInsertFromSelect(): Promise<InsertResult> {
     const queryRunner = this.obtainQueryRunner()
     let transactionStartedByUs: boolean = false
 
     try {
         // start transaction if it was enabled
         if (
             this.expressionMap.useTransaction === true &&
             queryRunner.isTransactionActive === false
         ) {
             await queryRunner.startTransaction()
             transactionStartedByUs = true
         }
 
         // execute query
         const [sql, parameters] = this.getQueryAndParameters()
         const queryResult = await queryRunner.query(sql, parameters, true)
 
         const insertResult = InsertResult.from(queryResult)
 
         // commit transaction if we started it
         if (transactionStartedByUs) {
-            await queryRunner.commitTransaction()
+            try {
+                await queryRunner.commitTransaction()
+            } catch (commitError) {
+                await queryRunner.rollbackTransaction()
+                throw commitError
+            }
         }
 
         return insertResult
     } catch (error) {
         // rollback transaction if we started it
-        if (transactionStartedByUs) {
+        if (transactionStartedByUs && queryRunner.isTransactionActive) {
             try {
                 await queryRunner.rollbackTransaction()
-            } catch (rollbackError) {}
+            } catch (rollbackError) {
+                // Log rollback error but throw original error
+            }
         }
         throw error
     } finally {
         if (queryRunner !== this.queryRunner) {
             // means we created our own query runner
             await queryRunner.release()
         }
     }
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a potential issue where a failed transaction commit is not handled correctly, which could leave the transaction in an open state. The proposed fix improves the reliability of transaction handling.

Medium
Validate SELECT column count exists

Improve validation by ensuring that if INSERT columns are specified, the SELECT
query must also have columns, and the counts must match.

src/query-builder/InsertQueryBuilder.ts [395-409]

 // Validate the number of selected columns matches the number of insert columns
 const selectColumnCount =
     selectQueryBuilder.expressionMap.selects.length
 const insertColumnCount = this.expressionMap.insertColumns.length
 
-// Only validate if both insert columns and select columns are explicitly specified
-if (insertColumnCount > 0 && selectColumnCount > 0) {
+// Validate if insert columns are explicitly specified
+if (insertColumnCount > 0) {
+    if (selectColumnCount === 0) {
+        throw new TypeORMError(
+            `No columns specified in the SELECT query, but ${insertColumnCount} column(s) ` +
+                `specified for INSERT. Make sure the SELECT query has columns specified.`,
+        )
+    }
     if (selectColumnCount !== insertColumnCount) {
         throw new TypeORMError(
             `The number of columns in the SELECT query (${selectColumnCount}) ` +
                 `does not match the number of columns specified for INSERT (${insertColumnCount}). ` +
                 `Make sure both have the same number of columns.`,
         )
     }
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a scenario where validation is missing, which would lead to a database error. The proposed change improves robustness by providing a clear error message to the developer.

Low
Validate callback returns SelectQueryBuilder

Add validation to ensure the callback function passed to valuesFromSelect
returns a valid SelectQueryBuilder instance to prevent potential runtime errors.

src/query-builder/InsertQueryBuilder.ts [373-393]

 valuesFromSelect(
     queryBuilderOrFactory:
         | SelectQueryBuilder<any>
         | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
 ): this {
     // Prevent using values and valuesFromSelect together
     if (this.expressionMap.valuesSet !== undefined) {
         throw new TypeORMError(
             `Cannot use both "values" and "valuesFromSelect" methods together. ` +
                 `Use either "values" to insert literal values or "valuesFromSelect" to insert from a SELECT query.`,
         )
     }
 
     let selectQueryBuilder: SelectQueryBuilder<any>
     if (typeof queryBuilderOrFactory === "function") {
         // Create a new SelectQueryBuilder and pass it to the factory
         const subQuery = this.createQueryBuilder().select()
         selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        if (!selectQueryBuilder || !InstanceChecker.isSelectQueryBuilder(selectQueryBuilder)) {
+            throw new TypeORMError(
+                `The callback function must return a valid SelectQueryBuilder instance.`,
+            )
+        }
     } else {
         selectQueryBuilder = queryBuilderOrFactory
     }
     ...
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that a faulty callback in valuesFromSelect can cause a runtime error. Adding validation improves developer experience by providing an immediate and clear error message.

Low
Suggestions up to commit bfc4128
CategorySuggestion                                                                                                                                    Impact
Possible issue
Add validation for insertFromSelect existence

Add a validation check at the beginning of the executeInsertFromSelect method to
ensure this.expressionMap.insertFromSelect is defined before execution.

src/query-builder/InsertQueryBuilder.ts [237-277]

 protected async executeInsertFromSelect(): Promise<InsertResult> {
+    if (!this.expressionMap.insertFromSelect) {
+        throw new TypeORMError(
+            "Cannot execute INSERT FROM SELECT: no SELECT query was specified. " +
+            "Use valuesFromSelect() to specify a SELECT query."
+        )
+    }
+
     const queryRunner = this.obtainQueryRunner()
     let transactionStartedByUs: boolean = false
 
     try {
         // start transaction if it was enabled
         if (
             this.expressionMap.useTransaction === true &&
             queryRunner.isTransactionActive === false
         ) {
             await queryRunner.startTransaction()
             transactionStartedByUs = true
         }
 
         // execute query
         const [sql, parameters] = this.getQueryAndParameters()
         const queryResult = await queryRunner.query(sql, parameters, true)
 
         const insertResult = InsertResult.from(queryResult)
 
         // commit transaction if we started it
         if (transactionStartedByUs) {
             await queryRunner.commitTransaction()
         }
 
         return insertResult
     } catch (error) {
         // rollback transaction if we started it
         if (transactionStartedByUs) {
             try {
                 await queryRunner.rollbackTransaction()
             } catch (rollbackError) {}
         }
         throw error
     } finally {
         if (queryRunner !== this.queryRunner) {
             // means we created our own query runner
             await queryRunner.release()
         }
     }
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion adds a defensive check. While the only call to executeInsertFromSelect() in the PR is already guarded by a check for this.expressionMap.insertFromSelect, adding this validation inside the protected method makes it more robust against future changes or incorrect usage by subclasses.

Low
Validate insertFromSelect before accessing it

In createInsertFromSelectExpression, add a validation check to ensure
this.expressionMap.insertFromSelect is defined before it is accessed, preventing
potential runtime errors.

src/query-builder/InsertQueryBuilder.ts [887-914]

 protected createInsertFromSelectExpression(): string {
+    if (!this.expressionMap.insertFromSelect) {
+        throw new TypeORMError(
+            "Cannot create INSERT FROM SELECT expression: no SELECT query was specified."
+        )
+    }
+
     const tableName = this.getTableName(this.getMainTableName())
 
     // Build the INSERT INTO part
     let query = "INSERT INTO " + tableName
 
     // Add column names if specified
     if (this.expressionMap.insertColumns.length > 0) {
         const columnsExpression = this.expressionMap.insertColumns
             .map((columnName) => this.escape(columnName))
             .join(", ")
         query += `(${columnsExpression})`
     } else if (this.expressionMap.mainAlias!.hasMetadata) {
         // Use metadata columns if available and no explicit columns specified
         const columns = this.getInsertedColumns()
         if (columns.length > 0) {
             const columnsExpression = columns
                 .map((column) => this.escape(column.databaseName))
                 .join(", ")
             query += `(${columnsExpression})`
         }
     }
 
     // Add the SELECT query (without wrapping in parentheses - standard SQL syntax)
-    query += " " + this.expressionMap.insertFromSelect!.getQuery()
+    query += " " + this.expressionMap.insertFromSelect.getQuery()
 
     return query
 }
Suggestion importance[1-10]: 3

__

Why: The suggestion adds a defensive check. The call to createInsertFromSelectExpression() is guarded in createInsertExpression(), making the non-null assertion ! safe. However, adding an explicit check within this protected method improves its robustness and makes it safer for potential future use or subclassing.

Low
✅ Suggestions up to commit c56364f
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Prevent using values and valuesFromSelect together
Suggestion Impact:The suggestion was implemented in the commit. The check was added to the values() method (lines 5-11) to throw a TypeORMError when insertFromSelect is already set. Additionally, a reciprocal check was added to the valuesFromSelect() method (lines 20-26) to prevent using values() after valuesFromSelect(). The error message was enhanced to be more descriptive than the suggested one.

code diff:

+        // Prevent using valuesFromSelect and values together
+        if (this.expressionMap.insertFromSelect) {
+            throw new TypeORMError(
+                `Cannot use both "values" and "valuesFromSelect" methods together. ` +
+                    `Use either "values" to insert literal values or "valuesFromSelect" to insert from a SELECT query.`,
+            )
+        }
+
         this.expressionMap.valuesSet = values
         return this
     }
@@ -367,14 +375,37 @@
             | SelectQueryBuilder<any>
             | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
     ): this {
+        // Prevent using values and valuesFromSelect together
+        if (this.expressionMap.valuesSet !== undefined) {
+            throw new TypeORMError(
+                `Cannot use both "values" and "valuesFromSelect" methods together. ` +
+                    `Use either "values" to insert literal values or "valuesFromSelect" to insert from a SELECT query.`,
+            )
+        }

In the values() method, add a check to throw an error if valuesFromSelect() has
already been called on the query builder.

src/query-builder/InsertQueryBuilder.ts [302-309]

 values(
     values:
         | QueryDeepPartialEntity<Entity>
         | QueryDeepPartialEntity<Entity>[],
 ): this {
+    if (this.expressionMap.insertFromSelect) {
+        throw new TypeORMError(
+            `Cannot use "values" and "valuesFromSelect" in the same query.`,
+        )
+    }
     this.expressionMap.valuesSet = values
     return this
 }
Suggestion importance[1-10]: 7

__

Why: This is a valid suggestion that improves the robustness of the new API by preventing mutually exclusive methods values() and valuesFromSelect() from being used together, which avoids developer confusion.

Medium

@Cprakhar
Cprakhar force-pushed the feat/support-insert-into-select-from branch 2 times, most recently from 29a62dc to bb1bc30 Compare January 7, 2026 11:37
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@coveralls

coveralls commented Jan 7, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.916% (+0.02%) from 80.901%
when pulling a39e57b on Cprakhar:feat/support-insert-into-select-from
into f66eee7 on typeorm:master.

@gioboa
gioboa requested review from G0maa, alumni and naorpeled January 7, 2026 22:00
@Cprakhar
Cprakhar force-pushed the feat/support-insert-into-select-from branch from bb1bc30 to 6cad117 Compare January 15, 2026 18:54
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

(Review updated until commit a39e57b)

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

Grey Divider


Action Required

1. Silent Column Mismatch in MERGE 🐞 Bug
Description
• When generating MERGE INTO source expressions for Oracle/SAP with INSERT FROM SELECT, column count
  mismatches are silently handled without validation
• If SELECT has more columns than target, extra columns are added without proper alias mapping
• If SELECT has fewer columns than target, some target columns have no corresponding SELECT
  expression
• This produces invalid SQL that fails at runtime or silently produces incorrect results, risking
  data integrity

correctness

Code

src/query-builder/InsertQueryBuilder.ts[R1274-1286]

+                originalSelects.forEach((select, index) => {
+                    const targetColumn = targetColumns[index]
+                    if (targetColumn) {
+                        // Add select with target column name as alias
+                        selectQb.expressionMap.selects.push({
+                            selection: select.selection,
+                            aliasName: targetColumn.databaseName,
+                            virtual: select.virtual,
+                        })
+                    } else {
+                        selectQb.expressionMap.selects.push(select)
+                    }
+                })
Evidence
The code iterates through originalSelects and maps them to targetColumns by index. When targetColumn
is undefined (more selects than targets), the else branch adds the select without proper aliasing.
When there are fewer selects than targets, some columns are unmapped. No validation exists to detect
or report these mismatches.

src/query-builder/InsertQueryBuilder.ts[1274-1286]
src/query-builder/InsertQueryBuilder.ts[1252-1299]

Agent Prompt
## Issue Description
When using INSERT FROM SELECT with MERGE INTO operations on Oracle/SAP databases, the code does not validate that the number of SELECT expressions matches the number of target INSERT columns. This can lead to incorrect SQL generation and runtime errors.

## Issue Context
The createMergeIntoSourceExpression method handles INSERT FROM SELECT for MERGE operations. For Oracle/SAP (non-MSSQL drivers), it clones the SelectQueryBuilder and maps select expressions to target columns by index. However, it doesn&#x27;t validate that the counts match.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1252-1299]: Add validation before the forEach loop to check originalSelects.length === targetColumns.length
- src/query-builder/InsertQueryBuilder.ts[1274-1286]: The forEach loop that maps selects to columns - add error handling for mismatches

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



Remediation Recommended

2. `valuesFromSelect` lacks null/undefined validation 📘 Rule Violation
Description
• The valuesFromSelect method does not validate if the input parameter is null or undefined before
  processing
• If a null or undefined value is passed, it could lead to runtime errors when attempting to call
  getParameters() or getQuery() on the undefined object
• This violates robust error handling practices by not checking edge cases at the method boundary

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R284-300]

+    valuesFromSelect(
+        queryBuilderOrFactory:
+            | SelectQueryBuilder<any>
+            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
+    ): this {
+        let selectQueryBuilder: SelectQueryBuilder<any>
+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
+            selectQueryBuilder = queryBuilderOrFactory
+        }
+        this.setParameters(selectQueryBuilder.getParameters())
+        this.expressionMap.insertFromSelect = selectQueryBuilder
+
+        return this
+    }
Evidence
The compliance rule requires explicit handling of null, empty, and boundary values. The
valuesFromSelect method accepts a parameter but does not validate if it's null or undefined before
using it. Lines 292 and 294 directly use the parameter without null checks, and line 296 calls
getParameters() which would fail if the object is null/undefined.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/InsertQueryBuilder.ts[289-296]

Agent Prompt
## Issue description
The `valuesFromSelect` method does not validate if the input parameter is null or undefined, which could lead to runtime errors when the method attempts to call `getParameters()` or `getQuery()` on an undefined object.

## Issue Context
This is a public API method that accepts user input. Following the pattern used elsewhere in the codebase (like the `returning` method which validates driver support), we should validate inputs at method boundaries.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[284-300]

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


3. `valuesFromSelect` callback lacks error handling 📘 Rule Violation
Description
• When using the callback function variant, if the callback throws an error or returns
  null/undefined, there is no error handling
• The method does not wrap the callback invocation in a try-catch block to provide meaningful
  context if the callback fails
• This could result in cryptic error messages that don't indicate the failure occurred within the
  valuesFromSelect callback

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R290-293]

+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
Evidence
The compliance rule requires that all potential failure points are identified and handled
appropriately with meaningful context. The callback invocation at line 292 is a potential failure
point but has no error handling to provide context about what failed and why.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/InsertQueryBuilder.ts[290-293]

Agent Prompt
## Issue description
The callback function invocation in `valuesFromSelect` lacks error handling and validation of the return value, which could lead to unclear error messages if the callback fails or returns an invalid value.

## Issue Context
User-provided callbacks are a common source of errors. The method should catch errors from the callback and provide meaningful context, and should also validate that the callback returns a valid SelectQueryBuilder instance.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[290-293]

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


4. Mutating Cloned SelectQueryBuilder State 🐞 Bug
Description
• The MERGE INTO source expression generation directly mutates the cloned SelectQueryBuilder's
  internal expressionMap.selects array
• This bypasses the SelectQueryBuilder's public API methods (select(), addSelect()) designed for
  managing selections
• Direct state mutation violates encapsulation and could cause inconsistencies if SelectQueryBuilder
  maintains derived state or caches
• While tests pass, this creates fragile code that could break if SelectQueryBuilder's internal
  implementation changes

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R1263-1288]

+                // Clone the SelectQueryBuilder and modify its select expressions
+                const selectQb = this.expressionMap.insertFromSelect.clone()
+                const targetColumns = this.getInsertedColumns()
+
+                // Clear existing selects and add new ones with proper aliases
+                selectQb.expressionMap.selects = []
+
+                // Get the original select expressions
+                const originalSelects =
+                    this.expressionMap.insertFromSelect.expressionMap.selects
+
+                originalSelects.forEach((select, index) => {
+                    const targetColumn = targetColumns[index]
+                    if (targetColumn) {
+                        // Add select with target column name as alias
+                        selectQb.expressionMap.selects.push({
+                            selection: select.selection,
+                            aliasName: targetColumn.databaseName,
+                            virtual: select.virtual,
+                        })
+                    } else {
+                        selectQb.expressionMap.selects.push(select)
+                    }
+                })
+
+                expression += selectQb.getQuery()
Evidence
The code clones a SelectQueryBuilder and then directly manipulates its expressionMap.selects array
by clearing it and pushing new select objects. The SelectQueryBuilder class provides public methods
for managing selections, but this code bypasses those methods and directly mutates internal state,
violating encapsulation principles.

src/query-builder/InsertQueryBuilder.ts[1263-1288]
src/query-builder/SelectQueryBuilder.ts[157-224]

Agent Prompt
## Issue Description
The code directly mutates the cloned SelectQueryBuilder&#x27;s internal expressionMap.selects array, bypassing the public API and violating encapsulation principles.

## Issue Context
When generating MERGE INTO source expressions for Oracle/SAP databases with INSERT FROM SELECT, the code needs to modify the SELECT query to add proper column aliases. Currently, it directly manipulates the internal state of a cloned SelectQueryBuilder.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1263-1288]: Refactor to either use SelectQueryBuilder&#x27;s public methods or create a new SelectQueryBuilder with the correct selects from the start
- src/query-builder/SelectQueryBuilder.ts[157-224]: Consider adding a public method for bulk-setting select expressions with aliases if needed

ⓘ 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 49f9445


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

Grey Divider
Action Required
1. MERGE INTO Fallback Logic Bug 🐞 Bug
Description
• When using orIgnore() with INSERT FROM SELECT on Oracle/SAP/MSSQL databases, if no primary key
  or unique constraints exist, the code falls back to matching on ALL inserted columns
• This means the MERGE will only match if every single column value is identical, which is unlikely
  and defeats the purpose of orIgnore()
• The correct behavior should be to throw an error indicating that orIgnore() requires at least
  one unique constraint to be defined
• This can cause unexpected insert failures when users expect duplicates to be ignored

correctness

Code

src/query-builder/InsertQueryBuilder.ts[R1099-1113]

+                if (allUniqueConditions.length > 0) {
+                    query += ` ON (${allUniqueConditions.join(" OR ")})`
+                } else {
+                    // Fallback: use all columns being inserted as the match condition
+                    const columnConditions = columns
+                        .map((column) => {
+                            return `${tableAlias}.${this.escape(
+                                column.databaseName,
+                            )} = ${mergeSourceAlias}.${this.escape(
+                                column.databaseName,
+                            )}`
+                        })
+                        .join(" AND ")
+                    query += ` ON (${columnConditions})`
+                }
Evidence
The code at lines 1099-1113 shows the fallback logic that uses ALL columns as the match condition
when no unique constraints are found. This is semantically incorrect because it requires every
column to match exactly, making it nearly impossible to detect actual duplicates. The test at line
508-560 in insert-from-select.test.ts passes because ArchivedUser entity has a unique constraint on
the email column (line 13 of ArchivedUser.ts), so this fallback path is never triggered in tests.

src/query-builder/InsertQueryBuilder.ts[1099-1113]
test/functional/query-builder/insert-from-select/entity/ArchivedUser.ts[13-14]

Agent Prompt
## Issue Description
The MERGE INTO fallback logic incorrectly uses ALL columns as the match condition when no unique constraints exist. This defeats the purpose of orIgnore() and can cause unexpected behavior.

## Issue Context
When using orIgnore() with INSERT FROM SELECT on Oracle/SAP/MSSQL databases (which use MERGE INTO), the code should require at least one unique constraint to determine which rows are duplicates. Without unique constraints, there&#x27;s no meaningful way to detect conflicts.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1099-1113]: Replace the fallback logic with an error throw
- Add validation to check if unique constraints exist before allowing orIgnore() with MERGE INTO
- Consider adding a test case for this error scenario

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


2. Incomplete Generated Column Filtering 🐞 Bug
Description
• Generated columns are only filtered out for specific databases (SQLite, MySQL, Aurora MySQL,
  Oracle) when using INSERT FROM SELECT
• PostgreSQL and MSSQL also have generated/computed columns that cannot be inserted into, but they
  are not included in this check
• This will cause SQL execution errors when using INSERT FROM SELECT on PostgreSQL or MSSQL tables
  with generated columns
• The inconsistency suggests incomplete implementation across database drivers

correctness

Code

src/query-builder/InsertQueryBuilder.ts[R789-799]

+                // Skip generated columns if we are inserting from select, if not explicitly specified
+                if (
+                    column.isGenerated &&
+                    this.expressionMap.insertFromSelect &&
+                    (DriverUtils.isSQLiteFamily(this.connection.driver) ||
+                        DriverUtils.isMySQLFamily(this.connection.driver) ||
+                        this.connection.driver.options.type ===
+                            "aurora-mysql" ||
+                        this.connection.driver.options.type === "oracle")
+                )
+                    return false
Evidence
The code at lines 789-799 shows that generated columns are only filtered for specific database
types. However, both PostgreSQL and MSSQL support generated columns (PostgreSQL has GENERATED ALWAYS
AS STORED, MSSQL has COMPUTED columns). The driver code confirms this: PostgresQueryRunner.ts
handles generatedType at lines 543-547 and 1115-1128, and SqlServerQueryRunner.ts handles
generatedType at lines 636-640 and 1157-1170. The ColumnMetadata class at line 193 defines
generatedType as 'VIRTUAL' | 'STORED', which is used by both databases. Without filtering these
columns, INSERT FROM SELECT will fail with SQL errors on these databases.

src/query-builder/InsertQueryBuilder.ts[789-799]
src/metadata/ColumnMetadata.ts[193-193]

Agent Prompt
## Issue Description
Generated columns are not properly filtered for PostgreSQL and MSSQL when using INSERT FROM SELECT, which will cause SQL execution errors.

## Issue Context
PostgreSQL supports GENERATED ALWAYS AS STORED columns, and MSSQL supports COMPUTED columns. Both databases prohibit inserting into these columns. The current code only filters generated columns for SQLite, MySQL, Aurora MySQL, and Oracle.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[789-799]: Extend the database type check to include PostgreSQL, MSSQL, and CockroachDB
- Alternatively, use a more generic check based on column.generatedType property to make it database-agnostic
- Consider checking column.generatedType === &#x27;STORED&#x27; specifically, as VIRTUAL columns don&#x27;t need filtering

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



Remediation Recommended
3. `valuesFromSelect` missing input validation 📘 Rule Violation
Description
• The valuesFromSelect method accepts a SelectQueryBuilder or callback function without
  validating that the input is not null or undefined
• Missing validation could lead to runtime errors when the method attempts to call getParameters()
  on a null/undefined value
• No checks exist to ensure the SelectQueryBuilder is properly configured before being used in SQL
  generation

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R284-300]

+    valuesFromSelect(
+        queryBuilderOrFactory:
+            | SelectQueryBuilder<any>
+            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
+    ): this {
+        let selectQueryBuilder: SelectQueryBuilder<any>
+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
+            selectQueryBuilder = queryBuilderOrFactory
+        }
+        this.setParameters(selectQueryBuilder.getParameters())
+        this.expressionMap.insertFromSelect = selectQueryBuilder
+
+        return this
+    }
Evidence
The compliance rule requires comprehensive error handling with explicit handling of null, empty, and
boundary values. The valuesFromSelect implementation directly uses the input parameters without
any validation checks, unlike other methods in the codebase that validate inputs. The method
immediately calls getParameters() and stores the query builder without checking if it's null or
undefined.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/InsertQueryBuilder.ts[284-300]

Agent Prompt
## Issue description
The `valuesFromSelect` method lacks input validation for null/undefined values and doesn&#x27;t validate the SelectQueryBuilder returned from callback functions.

## Issue Context
This is a new public API method that accepts external input. Without validation, null or undefined inputs could cause runtime errors when calling `getParameters()` or during SQL generation.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[284-300]

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


4. Missing Column Count Validation 🐞 Bug
Description
• The valuesFromSelect() method does not validate that the number of columns in the SELECT query
  matches the number of columns specified in the INSERT statement
• This can lead to SQL errors at runtime with potentially unclear error messages
• Early validation would provide better developer experience by catching this common mistake before
  query execution
• The database will ultimately reject the query, but a clear validation error would be more helpful

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R284-300]

+    valuesFromSelect(
+        queryBuilderOrFactory:
+            | SelectQueryBuilder<any>
+            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
+    ): this {
+        let selectQueryBuilder: SelectQueryBuilder<any>
+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
+            selectQueryBuilder = queryBuilderOrFactory
+        }
+        this.setParameters(selectQueryBuilder.getParameters())
+        this.expressionMap.insertFromSelect = selectQueryBuilder
+
+        return this
+    }
Evidence
The valuesFromSelect method at lines 284-300 accepts a SelectQueryBuilder and directly assigns it to
expressionMap.insertFromSelect without any validation. There's no check to ensure the number of
selected columns matches the number of target insert columns. While the database will catch this
error at execution time, adding validation here would provide a better developer experience with
clearer error messages. The SelectQueryBuilder.ts file at line 2162 has a TODO comment indicating
that validation for missing selects or FROM clause is a known gap.

src/query-builder/InsertQueryBuilder.ts[284-300]

Agent Prompt
## Issue Description
The valuesFromSelect method doesn&#x27;t validate that the SELECT column count matches the INSERT column count, leading to runtime database errors that could be caught earlier.

## Issue Context
When developers use INSERT FROM SELECT, they might accidentally specify a different number of columns in the SELECT than in the INSERT. This is a common mistake that should be caught early with a clear error message.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[284-300]: Add validation after line 297 to compare selectQueryBuilder.expressionMap.selects.length with this.getInsertedColumns().length
- Throw a descriptive TypeORMError if the counts don&#x27;t match
- Consider edge cases like SELECT * which might have dynamic column counts

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


Grey Divider
Results up to commit 6cad117


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

Grey Divider
Action Required
1. Empty SELECT crashes MERGE INTO 🐞 Bug
Description
• The createMergeIntoSourceExpression method directly accesses expressionMap.selects without
  checking if it exists or is empty
• If a SelectQueryBuilder is created without calling .select(), the selects array will be empty,
  causing the forEach loop to produce incorrect SQL
• This can lead to runtime crashes or malformed SQL queries in MERGE INTO operations with INSERT
  FROM SELECT

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R1254-1270]

+                // Get the original select expressions
+                const originalSelects =
+                    this.expressionMap.insertFromSelect.expressionMap.selects
+
+                originalSelects.forEach((select, index) => {
+                    const targetColumn = targetColumns[index]
+                    if (targetColumn) {
+                        // Add select with target column name as alias
+                        selectQb.expressionMap.selects.push({
+                            selection: select.selection,
+                            aliasName: targetColumn.databaseName,
+                            virtual: select.virtual,
+                        })
+                    } else {
+                        selectQb.expressionMap.selects.push(select)
+                    }
+                })
Evidence
The code accesses this.expressionMap.insertFromSelect.expressionMap.selects without validation.
The selects array is initialized as empty in QueryExpressionMap (line 63), so if a user creates a
SelectQueryBuilder without calling select(), the array will be empty. The forEach loop will then not
add any select expressions, resulting in malformed SQL.

src/query-builder/QueryExpressionMap.ts[63-63]
src/query-builder/InsertQueryBuilder.ts[1254-1270]

Agent Prompt
## Issue Description
The `createMergeIntoSourceExpression` method accesses `expressionMap.selects` without validating it&#x27;s not empty, which can cause malformed SQL in MERGE INTO operations.

## Issue Context
When using INSERT FROM SELECT with MERGE INTO (for orUpdate/orIgnore on Oracle/SAP/MSSQL), the code needs to clone and modify the SELECT query. If the SelectQueryBuilder has no select expressions, this produces invalid SQL.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1247-1273]: Add validation before accessing originalSelects
- src/query-builder/InsertQueryBuilder.ts[284-300]: Consider adding validation in valuesFromSelect() to ensure the SelectQueryBuilder has select expressions

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


2. MERGE INTO fallback matches all columns 🐞 Bug
Description
• When using orIgnore() with entities that have no unique constraints or indices, the MERGE INTO
  logic falls back to using ALL inserted columns for the ON condition
• This creates an overly restrictive match requiring every column to be identical, which defeats the
  purpose of duplicate detection
• Users expect duplicate detection based on natural keys, but will get unexpected duplicate rows
  when any column differs

correctness

Code

src/query-builder/InsertQueryBuilder.ts[R1086-1096]

+                    // Fallback: use all columns being inserted as the match condition
+                    const columnConditions = columns
+                        .map((column) => {
+                            return `${tableAlias}.${this.escape(
+                                column.databaseName,
+                            )} = ${mergeSourceAlias}.${this.escape(
+                                column.databaseName,
+                            )}`
+                        })
+                        .join(" AND ")
+                    query += ` ON (${columnConditions})`
Evidence
The code checks for unique constraints and indices, but if none exist, it falls back to using all
columns in the ON condition. This is demonstrated in the test entity UserPostSummary which has no
unique constraints - if this entity were used with orIgnore(), it would match on ALL columns (id,
userName, postCount) rather than a meaningful key. The comment 'Fallback: use all columns being
inserted as the match condition' confirms this is intentional but problematic behavior.

src/query-builder/InsertQueryBuilder.ts[1086-1096]
test/functional/query-builder/insert-from-select/entity/UserPostSummary.ts[1-15]

Agent Prompt
## Issue Description
The MERGE INTO fallback logic uses ALL columns for duplicate detection when no unique constraints exist, which is overly restrictive and unexpected.

## Issue Context
When using orIgnore() or orUpdate() with MERGE INTO on entities without unique constraints, the code should either:
1. Throw a clear error requiring users to define unique constraints
2. Use only the primary key for matching (if it exists)
3. Document this behavior clearly

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1083-1097]: Modify the fallback logic to use primary key only or throw an error
- src/query-builder/InsertQueryBuilder.ts[1036-1042]: Consider checking for primary key before falling back

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



Remediation Recommended
3. `valuesFromSelect` lacks null/undefined validation 📘 Rule Violation
Description
• The valuesFromSelect method accepts a SelectQueryBuilder or callback function but does not
  validate if the input is null, undefined, or if the callback returns null/undefined
• This could lead to runtime errors when the code attempts to call getParameters() on a
  null/undefined object at line 296
• Without proper validation, the system may fail silently or produce cryptic error messages that are
  difficult to debug

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R284-300]

+    valuesFromSelect(
+        queryBuilderOrFactory:
+            | SelectQueryBuilder<any>
+            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
+    ): this {
+        let selectQueryBuilder: SelectQueryBuilder<any>
+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
+            selectQueryBuilder = queryBuilderOrFactory
+        }
+        this.setParameters(selectQueryBuilder.getParameters())
+        this.expressionMap.insertFromSelect = selectQueryBuilder
+
+        return this
+    }
Evidence
The compliance rule requires comprehensive error handling with explicit handling of
null/empty/boundary cases. The valuesFromSelect method at lines 284-300 does not validate its
input parameter or the callback return value before using them, which violates the requirement for
edge case management.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/InsertQueryBuilder.ts[289-297]

Agent Prompt
## Issue description
The `valuesFromSelect` method does not validate its input parameter or callback return value, which could lead to runtime errors when null or undefined values are passed.

## Issue Context
This is a new method that accepts either a SelectQueryBuilder instance or a callback function. Without validation, calling `getParameters()` on null/undefined will throw a runtime error.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[284-300]

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


4. No column count validation between INSERT and SELECT 📘 Rule Violation
Description
• The implementation does not validate that the number of columns in the INSERT statement matches
  the number of columns in the SELECT query
• A mismatch between INSERT and SELECT column counts will result in database-level errors that are
  harder to debug
• This violates the requirement for comprehensive error handling with meaningful context about what
  failed

reliability

Code

src/query-builder/InsertQueryBuilder.ts[R284-300]

+    valuesFromSelect(
+        queryBuilderOrFactory:
+            | SelectQueryBuilder<any>
+            | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>),
+    ): this {
+        let selectQueryBuilder: SelectQueryBuilder<any>
+        if (typeof queryBuilderOrFactory === "function") {
+            const subQuery = this.createQueryBuilder().select()
+            selectQueryBuilder = queryBuilderOrFactory(subQuery)
+        } else {
+            selectQueryBuilder = queryBuilderOrFactory
+        }
+        this.setParameters(selectQueryBuilder.getParameters())
+        this.expressionMap.insertFromSelect = selectQueryBuilder
+
+        return this
+    }
Evidence
The compliance rule requires that all potential failure points are identified and handled
appropriately with error messages providing actionable context. The valuesFromSelect method does
not validate that the SELECT query's column count matches the INSERT column count, which is a common
error scenario that should be caught early.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/query-builder/InsertQueryBuilder.ts[296-297]

Agent Prompt
## Issue description
The `valuesFromSelect` method does not validate that the SELECT query returns the same number of columns as specified in the INSERT statement, leading to database errors.

## Issue Context
When using INSERT INTO ... SELECT FROM, the column counts must match. Without validation, users will get cryptic database errors instead of clear validation messages.

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[284-300]

ⓘ 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 49f9445

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

Wow @Cprakhar, nice job!

@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 👏 thank you @Cprakhar

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

Copy link
Copy Markdown

Persistent review updated to latest commit a39e57b

@gioboa
gioboa merged commit 8fc0915 into typeorm:master Jan 16, 2026
38 checks passed
@Cprakhar
Cprakhar deleted the feat/support-insert-into-select-from branch January 24, 2026 20:07
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.

Allow INSERT ... SELECT FROM

5 participants