Skip to content

fix: specify columns for metadata-less multi-value inserts - #11855

Open
Cprakhar wants to merge 6 commits into
typeorm:masterfrom
Cprakhar:fix/metadata-less-insert-columns
Open

Cprakhar wants to merge 6 commits into
typeorm:masterfrom
Cprakhar:fix/metadata-less-insert-columns

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Dec 18, 2025 •

Copy link
Copy Markdown
Collaborator

Description of change

  • Fix InsertQueryBuilder to always emit column lists for metadata-less multi-row inserts.
  • Add regression coverage for manager.insert() and QueryBuilder inserts without entity metadata.

Pull-Request Checklist

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

Fixes #3837

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

3837 - PR Code Verified

Compliant requirements:

  • Fix manager.insert() to generate correct SQL when inserting multiple rows into a table without entity metadata
  • Ensure column names are specified in the INSERT query for multi-row inserts
  • Remove or fix the if (valueSets.length === 1) check that causes columns to be omitted for multi-row inserts
  • Support inserting data using connection.manager.insert() with table name as string

Requires further human verification:

  • Verify that the generated SQL matches the expected format INSERT INTO difficulties (type) VALUES ('Easy'), ('Medium'), ('Hard') through actual database execution
  • Confirm that auto-generated columns (like id) are properly handled and generated by the database
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Column Order Consistency

The new getColumnNamesFromValueSets method iterates through all value sets and adds columns in the order they are encountered. If different value sets have columns in different orders or some value sets are missing columns that others have, this could lead to misaligned VALUES clauses where column positions don't match the column list order.

protected getColumnNamesFromValueSets(
    valueSets: ObjectLiteral[],
): string[] {
    const columns: string[] = []
    valueSets.forEach((valueSet) => {
        Object.keys(valueSet).forEach((columnName) => {
            if (columns.indexOf(columnName) === -1) {
                columns.push(columnName)
            }
        })
    })
    return columns
}
Missing Column Handling

When building the VALUES expression, the code assumes all columns from getColumnNamesFromValueSets exist in every valueSet. If a valueSet is missing a column that exists in another valueSet, valueSet[columnName] will be undefined, which may not be handled correctly and could lead to incorrect SQL generation or runtime errors.

columnNames.forEach((columnName, columnIndex) => {
    if (columnIndex === 0) {
        expression += "("
    }

@pkg-pr-new

pkg-pr-new Bot commented Dec 18, 2025 •

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

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

commit: fb3b9bf

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 90a5c70

CategorySuggestion                                                                                                                                    Impact
Possible issue
Respect explicit column ordering

In createValuesExpression, prioritize this.expressionMap.insertColumns for
determining column order when it is available. This ensures the generated values
align with the explicit columns specified in the INSERT statement for
metadata-less tables.

src/query-builder/InsertQueryBuilder.ts [954-1040]

 const columnNames =
-    this.derivedInsertColumns ||
-    this.getColumnNamesFromValueSets(valueSets)
+    this.expressionMap.insertColumns.length > 0
+        ? this.expressionMap.insertColumns
+        : this.derivedInsertColumns ||
+          this.getColumnNamesFromValueSets(valueSets)
 
 valueSets.forEach((valueSet, insertionIndex) => {
     columnNames.forEach((columnName, columnIndex) => {
         if (columnIndex === 0) {
             if (
                 this.connection.driver.options.type === "oracle" &&
                 valueSets.length > 1
             ) {
                 expression += " SELECT "
             } else if (
                 this.connection.driver.options.type === "sap" &&
                 valueSets.length > 1
             ) {
                 expression += " SELECT "
             } else {
                 expression += "("
             }
         }
 
         const value = valueSet[columnName]
         ...
     })
 })

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug where createValuesExpression does not respect the explicit column order provided via .into(), leading to a mismatch between the column list and the value list in the generated SQL. This is a critical correctness issue.

High
  • Update

Previous suggestions

Suggestions up to commit 6adef1b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use DEFAULT for missing values

In createValuesExpression, explicitly handle cases where a property is missing
from a value set by inserting the SQL DEFAULT keyword instead of passing
undefined to the parameter creator.

src/query-builder/InsertQueryBuilder.ts [948-994]

 valueSets.forEach((valueSet, insertionIndex) => {
     columnNames.forEach((columnName, columnIndex) => {
         if (columnIndex === 0) {
             expression += "("
         }
 
-... (clipped 12 lines)
+        const value = (valueSet as any)[columnName]
+
+        if (value === undefined) {
+            expression += "DEFAULT"
+        } else if (
+            value instanceof Function
+        ) {
+            // just any other regular value
         } else {
             expression += this.createParameter(value)
         }
 
         if (columnIndex === columnNames.length - 1) {
             if (insertionIndex === valueSets.length - 1) {
                 expression += ")"
             } else {
                 expression += "), "
             }
         } else {
             expression += ", "
         }
     })
 })
Suggestion importance[1-10]: 8

__

Why: This suggestion addresses a critical bug where missing properties in value sets result in undefined being passed to createParameter, which can cause inconsistent behavior or errors. Using DEFAULT for undefined values is the correct approach to let the database handle default values or nulls, significantly improving the robustness of the new feature.

Medium
Derive and cache column list

Populate the derivedInsertColumns cache within the values() method for
metadata-less inserts and ensure it is cleared on subsequent calls to prevent
stale state.

src/query-builder/InsertQueryBuilder.ts [263-270]

 values(
     values:
         | QueryDeepPartialEntity<Entity>
         | QueryDeepPartialEntity<Entity>[],
 ): this {
     this.expressionMap.valuesSet = values
+
+    // Keep derived columns in sync with current values for metadata-less inserts
+    this.derivedInsertColumns = undefined
+    if (
+        this.expressionMap.mainAlias &&
+        !this.expressionMap.mainAlias.hasMetadata &&
+        !this.expressionMap.insertColumns.length
+    ) {
+        const valueSets = Array.isArray(values) ? values : [values]
+        this.derivedInsertColumns =
+            this.getColumnNamesFromValueSets(valueSets as any)
+    }
+
     return this
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the new derivedInsertColumns property is read but never assigned a value, making the intended caching mechanism non-functional. Implementing this change correctly populates the cache, improving performance and ensuring the builder is reusable.

Medium
Assert that operation rejects

Refactor the test to use a promise rejection assertion
(expect(...).to.be.rejected) instead of a try/catch block to ensure the test
correctly fails if the insert operation does not throw an error as expected.

test/github-issues/3837/issue-3837.test.ts [198-241]

 it("should throw error on inserts with non-nullable columns not provided in values", () =>
     Promise.all(
         datasources.map(async (datasource) => {
             // Create a table with a non-nullable column
             const qr = datasource.createQueryRunner()
             await qr.createTable(
                 new Table({
                     name: "users",
                     columns: [
                         {
                             name: "id",
                             type: "int",
                             isPrimary: true,
                             isGenerated: true,
                             generationStrategy: "increment",
                         },
                         {
                             name: "username",
                             type: "varchar",
                             isNullable: false,
                         },
                         {
                             name: "email",
                             type: "varchar",
                             isNullable: false,
                         },
                     ],
                 }),
             )
             await qr.release()
 
-            try {
-                await datasource.manager.insert("users", [
+            await expect(
+                datasource.manager.insert("users", [
                     { username: "user1" },
                     { email: "[email protected]" },
                     { username: "user3", email: "[email protected]" },
-                ])
-            } catch (error) {
-                // Expect an error to be thrown due to missing non-nullable columns
-                expect(error).to.exist
-                return
-            }
+                ]),
+            ).to.be.rejected
         }),
     ))
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out a flaw in the test logic where a successful promise would lead to a passing test, which is the opposite of what's intended. Using a promise rejection assertion makes the test more robust and reliable.

Low
Suggestions up to commit d80a284
CategorySuggestion                                                                                                                                    Impact
Possible issue
Keep columns and values aligned

In createValuesExpression, when inserting into tables without metadata, use
this.expressionMap.insertColumns for the column list if it's available, instead
of always deriving columns from the value sets.

src/query-builder/InsertQueryBuilder.ts [933-989]

 } else {
     // for tables without metadata
     // get values needs to be inserted
     let expression = ""
-    const columnNames = this.getColumnNamesFromValueSets(valueSets)
+    const columnNames =
+        this.expressionMap.insertColumns.length > 0
+            ? this.expressionMap.insertColumns
+            : this.getColumnNamesFromValueSets(valueSets)
 
     valueSets.forEach((valueSet, insertionIndex) => {
         columnNames.forEach((columnName, columnIndex) => {
             if (columnIndex === 0) {
                 expression += "("
             }
 
             const value = valueSet[columnName]
             ...
         })
     })
     if (expression === "()") return ""
     return expression
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug where explicitly set columns are ignored when generating values, which can lead to invalid SQL or incorrect data insertion.

High
Insert NULL for missing fields

For metadata-less inserts, treat missing properties (undefined) as NULL instead
of DEFAULT to ensure consistent behavior and align with test expectations.

src/query-builder/InsertQueryBuilder.ts [960-973]

 const value = valueSet[columnName]
 
-if (value === undefined) {
-    expression += "DEFAULT"
-} else if (value === null) {
+if (value === undefined || value === null) {
     expression += "NULL"
-} else if (
-    typeof value === "function"
-) {
+} else if (typeof value === "function") {
     expression += value()
-} else if (
-    value instanceof Date
-) {
+} else if (value instanceof Date) {
     expression += this.createParameter(value)
-} else if (
-    value instanceof Buffer
-) {
+} else if (value instanceof Buffer) {
     expression += this.createParameter(value)
 } else {
     expression += this.createParameter(value)
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly points out that using DEFAULT for missing properties is inconsistent with the new test expectations and can cause issues, proposing to use NULL instead, which is a more robust approach.

Medium
Suggestions up to commit 98ad575
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use DEFAULT for missing values

For rows with missing properties in a bulk insert, use the SQL DEFAULT keyword
instead of binding an undefined parameter to allow the database to apply default
or null values.

src/query-builder/InsertQueryBuilder.ts [939-985]

 valueSets.forEach((valueSet, insertionIndex) => {
     columnNames.forEach((columnName, columnIndex) => {
         if (columnIndex === 0) {
             expression += "("
         }
 
         const value = valueSet[columnName]
 
-        if (
-            value === undefined &&
-            (this.connection.driver.options.type === "oracle" ||
-                this.connection.driver.options.type === "sap")
-        ) {
-            // just any other regular value
+        if (value === undefined) {
+            expression += "DEFAULT"
         } else {
             expression += this.createParameter(value)
         }
 
         if (columnIndex === columnNames.length - 1) {
             if (insertionIndex === valueSets.length - 1) {
                 expression += ")"
             } else {
                 expression += "), "
             }
         } else {
             expression += ", "
         }
     })
 })
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that binding undefined is not ideal and proposes using DEFAULT, which is semantically more correct for letting the database handle missing values.

Medium
General
Make derived column order deterministic

Sort the derived column names alphabetically in getColumnNamesFromValueSets to
ensure the generated SQL is deterministic, which improves statement caching and
test reliability.

src/query-builder/InsertQueryBuilder.ts [1012-1023]

 protected getColumnNamesFromValueSets(
     valueSets: ObjectLiteral[],
 ): string[] {
     const columns = new Set<string>()
     for (const valueSet of valueSets) {
         for (const columnName of Object.keys(valueSet)) {
             columns.add(columnName)
         }
     }
 
-    return Array.from(columns)
+    return Array.from(columns).sort()
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that the column order is non-deterministic, which can affect query caching and reproducibility; sorting the columns provides a simple and effective fix.

Low
Suggestions up to commit 72bf814
CategorySuggestion                                                                                                                                    Impact
Possible issue
Ensure deterministic column ordering

To prevent potential column-value mismatches in the generated SQL, sort the
column names in getColumnNamesFromValueSets to ensure a deterministic order.

src/query-builder/InsertQueryBuilder.ts [1012-1023]

 protected getColumnNamesFromValueSets(
     valueSets: ObjectLiteral[],
 ): string[] {
     const columns = new Set<string>()
     for (const valueSet of valueSets) {
         for (const columnName of Object.keys(valueSet)) {
             columns.add(columnName)
         }
     }
 
-    return Array.from(columns)
+    return Array.from(columns).sort()
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that createColumnNamesExpression and createValuesExpression independently generate column lists, and a non-deterministic order could cause data to be inserted into the wrong columns.

Medium
Handle missing columns in value sets

In createValuesExpression, explicitly handle cases where a column is missing in
a value set by coalescing the potentially undefined value to null to ensure
correct SQL generation.

src/query-builder/InsertQueryBuilder.ts [939-946]

 valueSets.forEach((valueSet, insertionIndex) => {
     columnNames.forEach((columnName, columnIndex) => {
         if (columnIndex === 0) {
             expression += "("
         }
 
-        const value = valueSet[columnName]
+        const value = columnName in valueSet ? valueSet[columnName] : null
         ...
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly points out that undefined values for missing keys in bulk inserts might not be handled correctly, and explicitly converting them to null ensures proper NULL insertion in the database.

Medium
Suggestions up to commit 800dca1
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle missing columns in value sets

In createValuesExpression, explicitly convert undefined values to null for
columns that are missing in a given valueSet to ensure correct SQL generation
for sparse inserts.

src/query-builder/InsertQueryBuilder.ts [939-946]

 valueSets.forEach((valueSet, insertionIndex) => {
     columnNames.forEach((columnName, columnIndex) => {
         if (columnIndex === 0) {
             expression += "("
         }
 
-        const value = valueSet[columnName]
+        const value = valueSet[columnName] !== undefined ? valueSet[columnName] : null
         ...
     })
 })
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies that undefined values for missing columns in sparse inserts can cause issues and proposes changing them to null, which is critical for generating correct SQL and ensuring the feature works as intended.

Medium

@coveralls

coveralls commented Dec 18, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.723% (-0.02%) from 73.745% — Cprakhar:fix/metadata-less-insert-columns into typeorm:master

Comment thread src/query-builder/InsertQueryBuilder.ts Resolved

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your help @Cprakhar
I added a small feedback.

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (12)   📘 Rule violations (8)   📎 Requirement gaps (0)   🎨 UX Issues (0)
🐞\ ≡ Correctness (11) ➹ Performance (1)
📘\ ≡ Correctness (7) ⚙ Maintainability (1) ⭐ New (1)

Grey Divider


Action required

1. Issue tests added under test/github-issues 📘 ⚙ ⭐
Description
New regression tests for this fix were added/expanded under test/github-issues/3837 instead of the
functional test suite. This violates the requirement to keep issue-fix coverage in test/functional
unless there is a clearly stated reason.
Code

test/github-issues/3837/issue-3837.test.ts[R22-73]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const qr = dataSource.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "integer",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+                await qr.release()
+
+                await dataSource.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                let sql: string
+                if (DriverUtils.isMySQLFamily(dataSource.driver)) {
+                    sql = `SELECT * FROM \`category\``
+                } else {
+                    sql = `SELECT * FROM "category"`
+                }
+
+                const result = await dataSource.query(sql)
+
+                const normalizedResult = result.map((row: any) => ({
+                    ...row,
+                    id: Number(row.id),
+                }))
+                expect(result).to.have.length(3)
+                expect(normalizedResult).to.deep.equal([
+                    { id: 1, name: "Easy" },
+                    { id: 2, name: "Medium" },
+                    { id: 3, name: "Hard" },
+                ])
+            }),
+        ))
+
Evidence
Compliance ID 3 requires issue fixes to add/update tests in test/functional, but this PR adds new
it(...) coverage in test/github-issues/3837/issue-3837.test.ts.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[22-73]

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 regression coverage for this fix is being added under `test/github-issues/...`, but the compliance checklist requires issue fixes to live in `test/functional` unless there is a clear reason.

## Issue Context
This PR expands `test/github-issues/3837/issue-3837.test.ts` with multiple new `it(...)` cases validating behavior.

## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[22-257]

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


2. Stale derived columns reused 🐞 ≡
Description
InsertQueryBuilder caches derivedInsertColumns in values(), but valuesFromSelect() does not clear
it, so a reused builder can emit an INSERT ... SELECT with an outdated column list. This can
generate invalid SQL or insert into the wrong target columns when switching from .values() to
.valuesFromSelect() on the same instance.
Code

src/query-builder/InsertQueryBuilder.ts[R271-280]

+        this.derivedInsertColumns = undefined
+        if (
+            !this.expressionMap.mainAlias?.hasMetadata &&
+            !this.expressionMap.insertColumns.length
+        ) {
+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
+        }
Evidence
values() now caches derivedInsertColumns, createColumnNamesExpression prefers this cached list, and
getValueSets() returns [] when insertFromSelect is set; however valuesFromSelect() does not reset
derivedInsertColumns, allowing stale columns from a prior .values() call to leak into an INSERT ...
SELECT query.

src/query-builder/InsertQueryBuilder.ts[265-321]
src/query-builder/InsertQueryBuilder.ts[836-856]
src/query-builder/InsertQueryBuilder.ts[1034-1037]

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

## Issue description
`InsertQueryBuilder` now caches `derivedInsertColumns` for metadata-less inserts in `.values()`, but `.valuesFromSelect()` does not reset that cache. If the same builder instance is reused and switched from value-based inserts to insert-from-select, the cached column list can be emitted even though `getValueSets()` becomes empty under `insertFromSelect`, producing incorrect/invalid `INSERT ... SELECT` SQL.
### Issue Context
- `derivedInsertColumns` is a new stateful cache.
- `valuesFromSelect()` mutates the builder to a different insert mode but does not clear the cache.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[265-321]
- src/query-builder/InsertQueryBuilder.ts[305-321]
- src/query-builder/InsertQueryBuilder.ts[836-856]
- src/query-builder/InsertQueryBuilder.ts[1034-1037]

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


3. Missing NOT NULL constraint validation 🐞 ≡
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


View more (10)
4. Insufficient Test Coverage Across Database Drivers 🐞 ≡
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 ≡
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 ≡
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Leaked QueryRunner in tests 🐞 ≡
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


8. try/catch test lacks assertion 📘 ≡
Description
The new test uses a try/catch and returns on error, but does not fail when no error is thrown, so
it can pass without validating behavior. This introduces noisy/defensive test code and weakens
regression coverage.
Code

test/github-issues/3837/issue-3837.test.ts[R229-240]

+                try {
+                    await datasource.manager.insert("users", [
+                        { username: "user1" },
+                        { email: "[email protected]" },
+                        { username: "user3", email: "[email protected]" },
+                    ])
+                } catch (error) {
+                    // Expect an error to be thrown due to missing non-nullable columns
+                    expect(error).to.exist
+                    return
+                }
+            }),
Evidence
The compliance rule disallows abnormal defensive try/catch patterns; here it also fails to assert
the expected rejection because the test has no failing path when the insert succeeds.

Rule 4: Remove AI-generated noise
test/github-issues/3837/issue-3837.test.ts[229-240]

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 test that expects an error uses a `try/catch` pattern that does not fail if the insert unexpectedly succeeds, so it may pass without actually enforcing the intended behavior.
## Issue Context
This is meant to be regression coverage for invalid inserts, so it must assert that the promise rejects (or explicitly fail when it does not).
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[229-240]

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


9. valueSets cast to any 📘 ≡
Description
The new metadata-less insert logic introduces an as any cast when deriving insert columns. This
can mask type issues and violates the rule against any casts added to bypass typing.
Code

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

+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
Evidence
PR Compliance ID 4 forbids adding any casts to bypass type checks. The diff adds `valueSets as
any when calling getColumnNamesFromValueSets`, which is exactly such a cast.

Rule 4: Remove AI-generated noise
src/query-builder/InsertQueryBuilder.ts[274-277]

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

## Issue description
`InsertQueryBuilder.values()` introduces `valueSets as any` to call `getColumnNamesFromValueSets`, which violates the compliance requirement to avoid `any` casts added to bypass typing.
## Issue Context
This code path is used for metadata-less inserts (`!mainAlias.hasMetadata`) and should still preserve type safety (or at least avoid `any`).
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[266-278]
- src/query-builder/InsertQueryBuilder.ts[1067-1078]

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


10. Test uses wrong quoting 🐞 ≡
Description
The new regression test hardcodes identifier quoting as MySQL backticks vs double-quotes for all
other drivers. This is incompatible with at least Spanner (which escapes identifiers with
backticks), and risks cross-driver CI failures now that the test no longer restricts to Postgres.
Code

test/github-issues/3837/issue-3837.test.ts[R53-58]

+                let sql: string
+                if (DriverUtils.isMySQLFamily(datasource.driver)) {
+                    sql = `SELECT * FROM \`category\``
+                } else {
+                    sql = `SELECT * FROM "category"`
+                }
Evidence
The test uses "table" for all non-MySQL drivers. But the Spanner driver explicitly escapes
identifiers with backticks, and the sample test config includes Spanner enabled by default (not
disabledIfNotEnabledImplicitly). With the PR removing the prior enabledDrivers: ["postgres"]
restriction, this test becomes more likely to execute against drivers where "table" is not the
correct escape syntax.

test/github-issues/3837/issue-3837.test.ts[53-58]
src/driver/spanner/SpannerDriver.ts[315-317]
ormconfig.sample.json[130-140]

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 test constructs raw SQL using only MySQL backticks vs double quotes for everything else, which is not portable across drivers (e.g., Spanner uses backticks).
### Issue Context
The test suite can run against multiple drivers (see `ormconfig.sample.json`), and this PR removed the previous Postgres-only restriction.
### Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[53-60]
- test/github-issues/3837/issue-3837.test.ts[112-120]
- test/github-issues/3837/issue-3837.test.ts[185-192]
- Replace hardcoded quoting with `datasource.driver.escape(&amp;quot;tableOrColumn&amp;quot;)` (and for ORDER BY, escape the column too), or use a TypeORM QueryBuilder SELECT to let the driver generate correct SQL.

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


11. values() needs mainAlias 🐞 ≡
Description
InsertQueryBuilder.values() now dereferences expressionMap.mainAlias and will throw if
.values() is called before .into(). This is a backwards-incompatible runtime regression for
fluent call orders that previously worked.
Code

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

+        this.derivedInsertColumns = undefined
+        if (
+            !this.expressionMap.mainAlias!.hasMetadata &&
+            !this.expressionMap.insertColumns.length
+        ) {
+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
Evidence
values() now assumes expressionMap.mainAlias is already initialized and accesses .hasMetadata,
but mainAlias is only set in .into(); QueryBuilder.insert() does not set it. Therefore
.insert().values(...).into(...) (or any .values() call before .into()) can crash before the
query is built.

src/query-builder/InsertQueryBuilder.ts[246-256]
src/query-builder/InsertQueryBuilder.ts[263-279]
src/query-builder/QueryBuilder.ts[201-210]

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

## Issue description
`InsertQueryBuilder.values()` dereferences `this.expressionMap.mainAlias!.hasMetadata`. If `values()` is invoked before `into()`, `mainAlias` can be undefined and will cause a runtime `TypeError`.
### Issue Context
`mainAlias` is initialized in `.into()`; `.insert()` alone does not set it.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[263-279]
- src/query-builder/InsertQueryBuilder.ts[246-256]
- src/query-builder/QueryBuilder.ts[201-210]
### Suggested change
- Replace `this.expressionMap.mainAlias!` usage in `values()` with a null-safe check:
- `const mainAlias = this.expressionMap.mainAlias;`
- Only derive columns if `mainAlias` exists and `!mainAlias.hasMetadata`.
- Keep existing fallback in `createColumnNamesExpression()`/`createValuesExpression()` so derived columns are still computed later when needed.

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


12. Test fails on Spanner 🐞 ≡
Description
The updated regression test no longer restricts enabledDrivers, so it will run on all configured
drivers, including Spanner in the default sample config. The test uses column types like
integer/varchar which Spanner won’t normalize and likely can’t create, causing the suite to fail
in environments where Spanner tests are enabled.
Code

test/github-issues/3837/issue-3837.test.ts[R16-36]

          (dataSources = await createTestingConnections({
              entities: [__dirname + "/entity/*{.js,.ts}"],
-                enabledDrivers: ["postgres"],
          })),
  )
  beforeEach(() => reloadTestingDatabases(dataSources))
  after(() => closeTestingConnections(dataSources))
-    xfail
-        .unless(() => dataSources.length > 0)
-        .it("should allow inserting named columns", () =>
-            Promise.all(
-                dataSources.map(async (connection) => {
-                    // Create the categories table.
-                    const qr = connection.createQueryRunner()
-                    await qr.createTable(
-                        new Table({
-                            name: "category",
-                            columns: [
-                                {
-                                    name: "id",
-                                    type: "int",
-                                    isPrimary: true,
-                                    isGenerated: true,
-                                    generationStrategy: "increment",
-                                },
-                                {
-                                    name: "name",
-                                    type: "varchar",
-                                },
-                            ],
-                        }),
-                    )
-
-                    const insert = connection.manager.insert("category", [
-                        { name: "Easy" },
-                        { name: "Medium" },
-                        { name: "Hard" },
+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            dataSources.map(async (connection) => {
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "integer",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
Evidence
When enabledDrivers is omitted, the test harness runs against every non-skipped driver in
ormconfig; ormconfig.sample.json includes Spanner with skip: false. The new test creates tables
with type: "integer"/"varchar". Spanner’s normalizeType returns unknown string types as-is, so
"integer" remains "integer" (not int64), which is not a Spanner supported type, making the table
creation (and thus the test) fail.

test/github-issues/3837/issue-3837.test.ts[14-18]
test/github-issues/3837/issue-3837.test.ts[28-41]
test/utils/test-utils.ts[236-254]
ormconfig.sample.json[130-140]
src/driver/spanner/SpannerDriver.ts[478-496]

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 regression test now runs across all configured drivers because `enabledDrivers` was removed. In the default configuration, Spanner is included and the test creates tables with `type: &amp;quot;integer&amp;quot;`/`&amp;quot;varchar&amp;quot;`, which Spanner does not normalize to supported types.
### Issue Context
`setupTestingConnections()` includes all drivers when `enabledDrivers` is omitted. `ormconfig.sample.json` includes Spanner with `skip: false`. Spanner `normalizeType()` returns unknown string types unchanged.
### Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[14-18]
- test/github-issues/3837/issue-3837.test.ts[28-41]

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


13. Stale derived columns cache 🐞 ≡
Description
derivedInsertColumns is computed once inside values() for metadata-less inserts and then preferred
later when building SQL. Because valuesSet is stored by reference and can be mutated after calling
.values() (or after calling execute() but before the query string is generated), the cached
derivedInsertColumns can diverge from the actual valueSets used, leading to ignored newly-added
columns or incorrect column/value alignment.
Code

src/query-builder/InsertQueryBuilder.ts[R269-278]

+        this.derivedInsertColumns = undefined
+        if (
+            !this.expressionMap.mainAlias?.hasMetadata &&
+            !this.expressionMap.insertColumns.length
+        ) {
+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
+        }
Evidence
InsertQueryBuilder stores the caller-provided values by reference and eagerly caches
derivedInsertColumns from that snapshot in values(). Later SQL generation prefers the cached list
over recomputing from the current getValueSets(), so any post-.values() mutation (e.g., pushing a
new row with an extra column) will not be reflected in the emitted column list or value ordering.

src/query-builder/InsertQueryBuilder.ts[263-280]
src/query-builder/InsertQueryBuilder.ts[951-957]
src/query-builder/InsertQueryBuilder.ts[858-867]

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

## Issue description
`derivedInsertColumns` is computed once in `values()` and later preferred when generating SQL. Since `valuesSet` is stored by reference, callers can mutate the values array/object after calling `.values()` (or after calling `.execute()` but before SQL generation runs). This can make `derivedInsertColumns` stale, causing newly-added columns/rows to be omitted or column/value alignment to be incorrect.
### Issue Context
- `values()` assigns `this.expressionMap.valuesSet = values` (no clone).
- `derivedInsertColumns` is computed in `values()` and later used via `this.derivedInsertColumns || ...`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[263-280]
- src/query-builder/InsertQueryBuilder.ts[851-877]
- src/query-builder/InsertQueryBuilder.ts[920-1044]
### Suggested direction
- Remove the eager computation in `values()` and compute column names from `this.getValueSets()` when building the query.
- Option A (simplest): stop using `derivedInsertColumns` entirely and always call `getColumnNamesFromValueSets(valueSets)` in both places.
- Option B: set `this.derivedInsertColumns = this.getColumnNamesFromValueSets(this.getValueSets())` inside `createInsertExpression()` (or at the start of `createValuesExpression()`), so it reflects the latest values and stays consistent for the current query build.

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



Remediation recommended

14. Non-deterministic column ordering in SQL generation 🐞 ≡
Description
• The getColumnNamesFromValueSets() method uses a Set to collect column names, relying on
Object.keys() enumeration order across different value objects • While modern JavaScript maintains
insertion order, the column order depends on which value object is processed first and their
property enumeration order • This creates implicit dependency on object property ordering rather
than explicit deterministic sorting • Can cause inconsistent SQL generation, debugging difficulties,
and potential issues with database drivers sensitive to column order
Code

src/query-builder/InsertQueryBuilder.ts[R1012-1023]

+    protected getColumnNamesFromValueSets(
+        valueSets: ObjectLiteral[],
+    ): string[] {
+        const columns = new Set<string>()
+        for (const valueSet of valueSets) {
+            for (const columnName of Object.keys(valueSet)) {
+                columns.add(columnName)
+            }
+        }
+
+        return Array.from(columns)
+    }
Evidence
The new method iterates through valueSets and uses Object.keys() to extract column names, adding
them to a Set which preserves insertion order. However, the final column order depends on the
enumeration order of Object.keys() across multiple objects. While this works in practice with modern
JavaScript engines, it's not explicitly deterministic. The test case at lines 149-158 demonstrates
heterogeneous column sets where different rows have different columns, but doesn't validate column
ordering consistency. The original code at lines 840-841 only handled single-row inserts, avoiding
this issue entirely.

src/query-builder/InsertQueryBuilder.ts[1012-1023]
test/github-issues/3837/issue-3837.test.ts[149-158]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The column ordering in bulk inserts depends on Object.keys() enumeration order across different value objects, making it implicitly non-deterministic. While it works in practice, explicit sorting would ensure consistent SQL generation.
## Issue Context
The `getColumnNamesFromValueSets()` method collects column names using a Set, which preserves insertion order. However, the insertion order depends on which value object is processed first and their property enumeration order.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1022-1022] - Change `return Array.from(columns)` to `return Array.from(columns).sort()` to ensure deterministic ordering

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


15. Tests in github-issues, not functional 📘 ≡
Description
• The fix for issue #3837 adds tests only in test/github-issues/3837/ directory without adding or
updating tests in test/functional/query-builder/insert/. • Compliance rule 3 requires issue fixes to
add or update tests in test/functional with an issue reference in the test comment when applicable.
• The functional test suite test/functional/query-builder/insert/query-builder-insert.test.ts exists
and covers insert operations but lacks coverage for metadata-less multi-row inserts, which is the
exact scenario this fix addresses.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                 ])
+                    .execute()
-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
The PR adds comprehensive test coverage for the bug fix, but places all tests in
test/github-issues/3837/ rather than in the functional test suite. Compliance rule 3 states that
issue fixes should stay in the functional test suite (test/functional) with an issue reference in
the test comment when applicable. The functional insert test suite at
test/functional/query-builder/insert/query-builder-insert.test.ts exists and would be the
appropriate location for these tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are currently in test/github-issues/3837/ but should be in the functional test suite per project conventions.
## Issue Context
Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue reference in the test comment when applicable. The functional insert test suite already exists at test/functional/query-builder/insert/query-builder-insert.test.ts.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-197]

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


16. Column union recomputed twice 🐞 ➹
Description
For metadata-less inserts without explicit columns, the derived union of column names is computed in
both createValuesExpression() and createColumnNamesExpression(), duplicating O(rows×cols) work
and relying on repeated enumeration consistency.
Code

src/query-builder/InsertQueryBuilder.ts[R848-854]

           const valueSets = this.getValueSets()
-            if (valueSets.length === 1)
-                return Object.keys(valueSets[0])
+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
+            if (columnNames.length > 0)
+                return columnNames
                   .map((columnName) => this.escape(columnName))
                   .join(", ")
       }
Evidence
The PR introduces getColumnNamesFromValueSets() and calls it in both column-name emission and
VALUES generation. Both methods are used during insert query generation, so the same column union is
computed twice for the same insert.

src/query-builder/InsertQueryBuilder.ts[843-854]
src/query-builder/InsertQueryBuilder.ts[933-941]
src/query-builder/InsertQueryBuilder.ts[1012-1023]

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

## Issue description
For metadata-less inserts (no explicit `insertColumns`), column names are derived twice from `valueSets`: once for the column list and once for VALUES. This duplicates work and depends on repeated enumeration producing identical results.
### Issue Context
Both `createValuesExpression()` and `createColumnNamesExpression()` are invoked during insert SQL generation.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[843-854]
- src/query-builder/InsertQueryBuilder.ts[933-941]
- src/query-builder/InsertQueryBuilder.ts[473-564]
### Suggested approaches
- Compute `columnNames...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 4261915 to 800dca1 Compare January 27, 2026 10:29
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 800dca1

@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

Copy link
Copy Markdown

Persistent review updated to latest commit 2d88c3e

@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

Copy link
Copy Markdown

Persistent review updated to latest commit 2578d37

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 2578d37 to 72bf814 Compare February 4, 2026 14:45
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 72bf814

@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, it looks great to me 👏

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Explicit columns order mismatch 🐞 Bug ✓ Correctness ⭐ New
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

            valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                    if (columnIndex === 0) {
                        expression += "("
                    }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

### Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&#x27;t&#x27;, [&#x27;a&#x27;,&#x27;b&#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.

### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.

### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]

### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
 - `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&#x27;t&#x27;, [&#x27;a&#x27;,&#x27;b&#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (2)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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



Remediation recommended

6. Column union recomputed twice 🐞 Bug ➹ Performance ⭐ New
Description
For metadata-less inserts without explicit columns, the derived union of column names is computed in
both createValuesExpression() and createColumnNamesExpression(), duplicating O(rows×cols) work
and relying on repeated enumeration consistency.
Code

src/query-builder/InsertQueryBuilder.ts[R848-854]

            const valueSets = this.getValueSets()
-            if (valueSets.length === 1)
-                return Object.keys(valueSets[0])
+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
+            if (columnNames.length > 0)
+                return columnNames
                    .map((columnName) => this.escape(columnName))
                    .join(", ")
        }
Evidence
The PR introduces getColumnNamesFromValueSets() and calls it in both column-name emission and
VALUES generation. Both methods are used during insert query generation, so the same column union is
computed twice for the same insert.

src/query-builder/InsertQueryBuilder.ts[843-854]
src/query-builder/InsertQueryBuilder.ts[933-941]
src/query-builder/InsertQueryBuilder.ts[1012-1023]

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

### Issue description
For metadata-less inserts (no explicit `insertColumns`), column names are derived twice from `valueSets`: once for the column list and once for VALUES. This duplicates work and depends on repeated enumeration producing identical results.

### Issue Context
Both `createValuesExpression()` and `createColumnNamesExpression()` are invoked during insert SQL generation.

### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[843-854]
- src/query-builder/InsertQueryBuilder.ts[933-941]
- src/query-builder/InsertQueryBuilder.ts[473-564]

### Suggested approaches
- Compute `columnNames` once and cache it on the builder instance (e.g. a private field reset per build), or
- Compute once inside `createInsertExpression()` and pass it down (requires refactor), or
- Store it in `expressionMap` for the duration of query generation.

### Acceptance criteria
- No behavior change.
- `getColumnNamesFromValueSets()` is called at most once per insert query build for the metadata-less/no-explicit-columns path.

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


7. Tests in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix for issue #3837 adds tests only in test/github-issues/3837/ directory without adding or
updating tests in test/functional/query-builder/insert/. • Compliance rule 3 requires issue fixes to
add or update tests in test/functional with an issue reference in the test comment when applicable.
• The functional test suite test/functional/query-builder/insert/query-builder-insert.test.ts exists
and covers insert operations but lacks coverage for metadata-less multi-row inserts, which is the
exact scenario this fix addresses.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                   ])
+                    .execute()

-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
The PR adds comprehensive test coverage for the bug fix, but places all tests in
test/github-issues/3837/ rather than in the functional test suite. Compliance rule 3 states that
issue fixes should stay in the functional test suite (test/functional) with an issue reference in
the test comment when applicable. The functional insert test suite at
test/functional/query-builder/insert/query-builder-insert.test.ts exists and would be the
appropriate location for these tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are currently in test/github-issues/3837/ but should be in the functional test suite per project conventions.
## Issue Context
Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue reference in the test comment when applicable. The functional insert test suite already exists at test/functional/query-builder/insert/query-builder-insert.test.ts.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-197]

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


8. Non-deterministic column ordering in SQL generation 🐞 Bug ⛯ Reliability
Description
• The getColumnNamesFromValueSets() method uses a Set to collect column names, relying on
Object.keys() enumeration order across different value objects • While modern JavaScript maintains
insertion order, the column order depends on which value object is processed first and their
property enumeration order • This creates implicit dependency on object property ordering rather
than explicit deterministic sorting • Can cause inconsistent SQL generation, debugging difficulties,
and potential issues with database drivers sensitive to column order
Code

src/query-builder/InsertQueryBuilder.ts[R1012-1023]

+    protected getColumnNamesFromValueSets(
+        valueSets: ObjectLiteral[],
+    ): string[] {
+        const columns = new Set<string>()
+        for (const valueSet of valueSets) {
+            for (const columnName of Object.keys(valueSet)) {
+                columns.add(columnName)
+            }
+        }
+
+        return Array.from(columns)
+    }
Evidence
The new method iterates through valueSets and uses Object.keys() to extract column names, adding
them to a Set which preserves insertion order. However, the final column order depends on the
enumeration order of Object.keys() across multiple objects. While this works in practice with modern
JavaScript engines, it's not explicitly deterministic. The test case at lines 149-158 demonstrates
heterogeneous column sets where different rows have different columns, but doesn't validate column
ordering consistency. The original code at lines 840-841 only handled single-row inserts, avoiding
this issue entirely.

src/query-builder/InsertQueryBuilder.ts[1012-1023]
test/github-issues/3837/issue-3837.test.ts[149-158]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The column ordering in bulk inserts depends on Object.keys() enumeration order across different value objects, making it implicitly non-deterministic. While it works in practice, explicit sorting would ensure consistent SQL generation.
## Issue Context
The `getColumnNamesFromValueSets()` method collects column names using a Set, which preserves insertion order. However, the insertion order depends on which value object is processed first and their property enumeration order.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1022-1022] - Change `return Array.from(columns)` to `return Array.from(columns).sort()` to ensure deterministic ordering

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


View more (6)
9. Tests in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix for issue #3837 adds tests only in test/github-issues/3837/ directory without adding or
updating tests in test/functional/query-builder/insert/. • Compliance rule 3 requires issue fixes to
add or update tests in test/functional with an issue reference in the test comment when applicable.
• The functional test suite test/functional/query-builder/insert/query-builder-insert.test.ts exists
and covers insert operations but lacks coverage for metadata-less multi-row inserts, which is the
exact scenario this fix addresses.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                  ])
+                    .execute()
-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
The PR adds comprehensive test coverage for the bug fix, but places all tests in
test/github-issues/3837/ rather than in the functional test suite. Compliance rule 3 states that
issue fixes should stay in the functional test suite (test/functional) with an issue reference in
the test comment when applicable. The functional insert test suite at
test/functional/query-builder/insert/query-builder-insert.test.ts exists and would be the
appropriate location for these tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are currently in test/github-issues/3837/ but should be in the functional test suite per project conventions.
## Issue Context
Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue reference in the test comment when applicable. The functional insert test suite already exists at test/functional/query-builder/insert/query-builder-insert.test.ts.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-197]

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


10. Tests in github-issues instead of functional 📘 Rule violation ✓ Correctness
Description
• The PR adds comprehensive tests for issue #3837 exclusively in test/github-issues/3837/ without
adding or updating tests in test/functional/query-builder/insert/. • Per compliance rule #3, issue
fixes should preferably add or update tests in the functional test suite with issue references in
comments. • The existing functional insert test file at
test/functional/query-builder/insert/query-builder-insert.test.ts would be the appropriate
location for these tests with a comment referencing issue #3837.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                  ])
+                    .execute()
-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
Compliance rule #3 states that issue fixes should add or update tests in test/functional with issue
references in comments when applicable. The PR adds three new test cases exclusively in the
github-issues directory without adding corresponding tests to the functional test suite. The
functional test directory already has a dedicated insert test file
(test/functional/query-builder/insert/query-builder-insert.test.ts) where these tests would fit
naturally.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are located only in test/github-issues/3837/ but should be in the functional test suite per project guidelines.
## Issue Context
Compliance rule #3 requires that issue fixes add or update tests in test/functional with issue references in comments. The project already has a functional insert test file where these tests belong.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-200]

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


11. @PARAM tags added without descriptions 📘 Rule violation ✓ Correctness
Description
• Multiple JSDoc comments were updated to add @param tags without descriptions (e.g., `@param
entityTarget, @param values, @param statement). • While the codebase does have some @param`
tags without descriptions, this appears to be inconsistent with the existing pattern where most
JSDoc comments either have no @param tags or have them with descriptions. • These additions don't
add meaningful documentation value and may be AI-generated noise.
Code

src/query-builder/InsertQueryBuilder.ts[R238-242]

+     * @param entityTarget
+     * @param columns
   */
  into<T extends ObjectLiteral>(
      entityTarget: EntityTarget<T>,
Evidence
Compliance rule #4 prohibits AI-generated noise including extra comments that are inconsistent with
file style. The PR adds multiple @param tags without descriptions across various JSDoc comments.
While some @param tags without descriptions exist in the codebase, the pattern in this file shows
that most methods either have no @param tags or have them with meaningful descriptions. Adding bare
@param tags without descriptions provides no documentation value and appears to be AI-generated
boilerplate.

Rule 4: Remove AI-generated noise
src/query-builder/InsertQueryBuilder.ts[238-239]
src/query-builder/InsertQueryBuilder.ts[256-256]
src/query-builder/InsertQueryBuilder.ts[286-286]

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

## Issue description
Multiple @param JSDoc tags were added without descriptions, which adds no documentation value and appears to be AI-generated noise.
## Issue Context
Compliance rule #4 requires removing AI-generated noise. The existing code style in this file shows that JSDoc comments either omit @param tags entirely or include them with meaningful descriptions. Adding bare @param tags is inconsistent with this pattern.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[238-239]
- src/query-builder/InsertQueryBuilder.ts[256-256]
- src/query-builder/InsertQueryBuilder.ts[286-286]
- src/query-builder/InsertQueryBuilder.ts[325-325]
- src/query-builder/InsertQueryBuilder.ts[350-350]
- src/query-builder/InsertQueryBuilder.ts[366-366]
- src/query-builder/InsertQueryBuilder.ts[375-375]
- src/query-builder/InsertQueryBuilder.ts[385-385]
- src/query-builder/InsertQueryBuilder.ts[417-419]
- src/query-builder/InsertQueryBuilder.ts[1010-1010]
- src/query-builder/InsertQueryBuilder.ts[1027-1027]
- src/query-builder/InsertQueryBuilder.ts[1270-1270]
- src/query-builder/InsertQueryBuilder.ts[1435-1435]
- src/query-builder/InsertQueryBuilder.ts[1481-1481]

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


12. Documentation not updated for bug fix 📘 Rule violation ✓ Correctness
Description
• The PR fixes a bug where manager.insert() with string table names and multiple records fails to
generate correct SQL with column names. • This is a user-facing change affecting the public API
behavior of manager.insert() and QueryBuilder inserts. • The PR checklist shows documentation was
not updated (checkbox unchecked), and no documentation changes are present in the diff.
Code

test/github-issues/3837/issue-3837.test.ts[R23-55]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
Evidence
The compliance rule requires documentation updates for user-facing changes. The PR description
explicitly states 'Documentation has been updated to reflect this change (docs/docs/**.md)' is
unchecked. The test demonstrates a user-facing API change where manager.insert() with string table
names now works correctly for multiple records. The existing documentation at
docs/docs/working-with-entity-manager/5-entity-manager-api.md only shows examples with entity
classes (User), not string table names, and doesn't mention the multi-record scenario with
metadata-less tables.

Rule 2: Docs updated for user-facing changes
test/github-issues/3837/issue-3837.test.ts[47-51]

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 documentation needs to be updated to reflect that manager.insert() now correctly handles multi-record inserts when using string table names (metadata-less tables) with auto-generated columns.
## Issue Context
This PR fixes issue #3837 where inserting multiple records into a table with auto-generated columns using string table names would fail. The fix ensures column names are properly included in the generated SQL. Users need to know this capability is now supported.
## Fix Focus Areas
- docs/docs/working-with-entity-manager/5-entity-manager-api.md[160-178]
- docs/docs/query-builder/2-insert-query-builder.md[1-20]

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


13. Test in github-issues not functional 📘 Rule violation ✓ Correctness
Description
• The test is located in test/github-issues/3837/ rather than test/functional/. • The compliance
rule prefers issue fixes to be added to the functional test suite with issue references in comments.
• While the test references issue #3837 in the describe block, it should be in the functional test
suite for better organization and maintainability.
Code

test/github-issues/3837/issue-3837.test.ts[11]

describe("github issues > #3837 named columns", () => {
Evidence
The compliance rule states that issue fixes should add or update tests in test/functional with an
issue reference in the test comment when applicable. The test is currently in
test/github-issues/3837/ directory. The functional test suite already has
test/functional/query-builder/insert/query-builder-insert.test.ts which would be the appropriate
location for these tests, with a comment referencing issue #3837.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[11-11]

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 #3837 should be moved to the functional test suite rather than remaining in test/github-issues/.
## Issue Context
The project prefers to keep issue fix tests in the functional test suite with issue references in comments. This improves test organization and maintainability. The tests verify that manager.insert() and QueryBuilder inserts work correctly with metadata-less multi-record inserts.
## Fix Focus Areas
- test/functional/query-builder/insert/query-builder-insert.test.ts[197-197]
- test/github-issues/3837/issue-3837.test.ts[23-107]

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


14. Inefficient O(n²) deduplication in getColumnNamesFromValueSets ☑ 🐞 Bug ➹...

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

Can you address the qodo feedback please?

@Cprakhar

Copy link
Copy Markdown
Collaborator Author

Can you address the qodo feedback please?

I will look into it.

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (15) 📘 Rule violations (12) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability ⭐ New
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.

## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.

## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]

## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

```ts
const qr = connection.createQueryRunner()
try {
 await qr.createTable(/*...*/)
} finally {
 await qr.release()
}
```

(Repeat for each test’s QueryRunner.)

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (7)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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



Remediation recommended

11. Tests in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix for issue #3837 adds tests only in test/github-issues/3837/ directory without adding or
updating tests in test/functional/query-builder/insert/. • Compliance rule 3 requires issue fixes to
add or update tests in test/functional with an issue reference in the test comment when applicable.
• The functional test suite test/functional/query-builder/insert/query-builder-insert.test.ts exists
and covers insert operations but lacks coverage for metadata-less multi-row inserts, which is the
exact scenario this fix addresses.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                   ])
+                    .execute()

-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
The PR adds comprehensive test coverage for the bug fix, but places all tests in
test/github-issues/3837/ rather than in the functional test suite. Compliance rule 3 states that
issue fixes should stay in the functional test suite (test/functional) with an issue reference in
the test comment when applicable. The functional insert test suite at
test/functional/query-builder/insert/query-builder-insert.test.ts exists and would be the
appropriate location for these tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are currently in test/github-issues/3837/ but should be in the functional test suite per project conventions.
## Issue Context
Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue reference in the test comment when applicable. The functional insert test suite already exists at test/functional/query-builder/insert/query-builder-insert.test.ts.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-197]

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


12. Non-deterministic column ordering in SQL generation 🐞 Bug ⛯ Reliability
Description
• The getColumnNamesFromValueSets() method uses a Set to collect column names, relying on
Object.keys() enumeration order across different value objects • While modern JavaScript maintains
insertion order, the column order depends on which value object is processed first and their
property enumeration order • This creates implicit dependency on object property ordering rather
than explicit deterministic sorting • Can cause inconsistent SQL generation, debugging difficulties,
and potential issues with database drivers sensitive to column order
Code

src/query-builder/InsertQueryBuilder.ts[R1012-1023]

+    protected getColumnNamesFromValueSets(
+        valueSets: ObjectLiteral[],
+    ): string[] {
+        const columns = new Set<string>()
+        for (const valueSet of valueSets) {
+            for (const columnName of Object.keys(valueSet)) {
+                columns.add(columnName)
+            }
+        }
+
+        return Array.from(columns)
+    }
Evidence
The new method iterates through valueSets and uses Object.keys() to extract column names, adding
them to a Set which preserves insertion order. However, the final column order depends on the
enumeration order of Object.keys() across multiple objects. While this works in practice with modern
JavaScript engines, it's not explicitly deterministic. The test case at lines 149-158 demonstrates
heterogeneous column sets where different rows have different columns, but doesn't validate column
ordering consistency. The original code at lines 840-841 only handled single-row inserts, avoiding
this issue entirely.

src/query-builder/InsertQueryBuilder.ts[1012-1023]
test/github-issues/3837/issue-3837.test.ts[149-158]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The column ordering in bulk inserts depends on Object.keys() enumeration order across different value objects, making it implicitly non-deterministic. While it works in practice, explicit sorting would ensure consistent SQL generation.
## Issue Context
The `getColumnNamesFromValueSets()` method collects column names using a Set, which preserves insertion order. However, the insertion order depends on which value object is processed first and their property enumeration order.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1022-1022] - Change `return Array.from(columns)` to `return Array.from(columns).sort()` to ensure deterministic ordering

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


13. Tests in github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix for issue #3837 adds tests only in test/github-issues/3837/ directory without adding or
updating tests in test/functional/query-builder/insert/. • Compliance rule 3 requires issue fixes to
add or update tests in test/functional with an issue reference in the test comment when applicable.
• The functional test suite test/functional/query-builder/insert/query-builder-insert.test.ts exists
and covers insert operations but lacks coverage for metadata-less multi-row inserts, which is the
exact scenario this fix addresses.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table with multiple nullable columns
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "tasks",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "description",
+                                type: "varchar",
+                                isNullable: true,
+                            },
+                            {
+                                name: "priority",
+                                type: "int",
+                                isNullable: true,
+                            },
+                        ],
+                    }),
+                )
+
+                // Insert rows with different subsets of columns
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("tasks")
+                    .values([
+                        {
+                            name: "Task 1",
+                            description: "First task",
+                            priority: 1,
+                        },
+                        { name: "Task 2" },
+                        { description: "No name", priority: 2 },
+                        { priority: 3 },
                  ])
+                    .execute()
-                    return expect(insert).to.fulfilled
-                }),
-            ),
-        )
+                // Verify all rows were inserted and missing columns are NULL
+                const rows = await connection.query(
+                    `SELECT * FROM tasks ORDER BY id ASC`,
+                )
+                expect(rows).to.have.length(4)
+                expect(rows).to.deep.equal([
+                    {
+                        id: 1,
+                        name: "Task 1",
+                        description: "First task",
+                        priority: 1,
+                    },
+                    {
+                        id: 2,
+                        name: "Task 2",
+                        description: null,
+                        priority: null,
+                    },
+                    { id: 3, name: null, description: "No name", priority: 2 },
+                    { id: 4, name: null, description: null, priority: 3 },
+                ])
+            }),
+        ))
Evidence
The PR adds comprehensive test coverage for the bug fix, but places all tests in
test/github-issues/3837/ rather than in the functional test suite. Compliance rule 3 states that
issue fixes should stay in the functional test suite (test/functional) with an issue reference in
the test comment when applicable. The functional insert test suite at
test/functional/query-builder/insert/query-builder-insert.test.ts exists and would be the
appropriate location for these tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/3837/issue-3837.test.ts[23-183]

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 #3837 are currently in test/github-issues/3837/ but should be in the functional test suite per project conventions.
## Issue Context
Compliance rule 3 requires issue fixes to add or update tests in test/functional with an issue reference in the test comment when applicable. The functional insert test suite already exists at test/functional/query-builder/insert/query-builder-insert.test.ts.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-183]
- test/functional/query-builder/insert/query-builder-insert.test.ts[1-197]

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


View more (13)
14. Tests in github-issues instead of functional 📘 Rule violation ✓ Correctness
Description
• The PR adds comprehensive tests for issue #3837 exclusively in test/github-issues/3837/ without
adding or updating tests in test/functional/query-builder/insert/. • Per compliance rule #3, issue
fixes should preferably add or update tests in the functional test suite with issue references in
comments. • The existing functional insert test file at
test/functional/query-builder/insert/query-builder-insert.test.ts would be the appropriate
location for these tests with a comment referencing issue #3837.
Code

test/github-issues/3837/issue-3837.test.ts[R23-183]

+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the categories table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const insert = connection.manager.insert("category", [
+                    { name: "Easy" },
+                    { name: "Medium" },
+                    { name: "Hard" },
+                ])
+
+                return expect(insert).to.fulfilled
+            }),
+        ))
+
+    it("should allow inserting named columns using queryBuilder with explicit columns", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create the difficulties table.
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "difficulty",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "type",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
+
+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
+
+                await connection.manager
+                    .createQueryBuilder()
+                    .insert()
+                    .into("difficulty", ["type"])
+                    .values(data)
+                    .execute()
+
+                const result = await connection.query(
+                    `SELECT COUNT(*) as count FROM difficulty`,
+                )
+                const count = parseInt(
+                    result[0].count ||
+                        result[0].COUNT ||
+                        result[0].count_ ||
+                        result[0].COUNT_,
+                    10,
+                )
+
+                return expect(count).to.equal(3)
+            }),
+        ))
+
+    it("should handle bulk inserts with different column sets and fill missing columns with NULL/default", () =>
+        Promise.all(
+            connections.map(async (connection) => {
+                // Create a table ...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from d80a284 to 6adef1b Compare February 25, 2026 11:35
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (26) 📘 Rule violations (15) 📎 Requirement gaps (0)

Grey Divider


Action required

1. try/catch test lacks assertion 📘 Rule violation ✓ Correctness ⭐ New
Description
The new test uses a try/catch and returns on error, but does not fail when no error is thrown, so
it can pass without validating behavior. This introduces noisy/defensive test code and weakens
regression coverage.
Code

test/github-issues/3837/issue-3837.test.ts[R229-240]

+                try {
+                    await datasource.manager.insert("users", [
+                        { username: "user1" },
+                        { email: "[email protected]" },
+                        { username: "user3", email: "[email protected]" },
+                    ])
+                } catch (error) {
+                    // Expect an error to be thrown due to missing non-nullable columns
+                    expect(error).to.exist
+                    return
+                }
+            }),
Evidence
The compliance rule disallows abnormal defensive try/catch patterns; here it also fails to assert
the expected rejection because the test has no failing path when the insert succeeds.

Rule 4: Remove AI-generated noise
test/github-issues/3837/issue-3837.test.ts[229-240]

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 test that expects an error uses a `try/catch` pattern that does not fail if the insert unexpectedly succeeds, so it may pass without actually enforcing the intended behavior.

## Issue Context
This is meant to be regression coverage for invalid inserts, so it must assert that the promise rejects (or explicitly fail when it does not).

## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[229-240]

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (17)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


11. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


12. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


13. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


14. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


15. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


16. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


17. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


18. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 6adef1b to 90a5c70 Compare February 25, 2026 12:58
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (43) 📘 Rule violations (16) 📎 Requirement gaps (0)

Grey Divider


Action required

1. valueSets cast to any 📘 Rule violation ✓ Correctness ⭐ New
Description
The new metadata-less insert logic introduces an as any cast when deriving insert columns. This
can mask type issues and violates the rule against any casts added to bypass typing.
Code

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

+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
Evidence
PR Compliance ID 4 forbids adding any casts to bypass type checks. The diff adds `valueSets as
any when calling getColumnNamesFromValueSets`, which is exactly such a cast.

Rule 4: Remove AI-generated noise
src/query-builder/InsertQueryBuilder.ts[274-277]

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

## Issue description
`InsertQueryBuilder.values()` introduces `valueSets as any` to call `getColumnNamesFromValueSets`, which violates the compliance requirement to avoid `any` casts added to bypass typing.

## Issue Context
This code path is used for metadata-less inserts (`!mainAlias.hasMetadata`) and should still preserve type safety (or at least avoid `any`).

## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[266-278]
- src/query-builder/InsertQueryBuilder.ts[1067-1078]

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


2. Test uses wrong quoting 🐞 Bug ⛯ Reliability ⭐ New
Description
The new regression test hardcodes identifier quoting as MySQL backticks vs double-quotes for all
other drivers. This is incompatible with at least Spanner (which escapes identifiers with
backticks), and risks cross-driver CI failures now that the test no longer restricts to Postgres.
Code

test/github-issues/3837/issue-3837.test.ts[R53-58]

+                let sql: string
+                if (DriverUtils.isMySQLFamily(datasource.driver)) {
+                    sql = `SELECT * FROM \`category\``
+                } else {
+                    sql = `SELECT * FROM "category"`
+                }
Evidence
The test uses "table" for all non-MySQL drivers. But the Spanner driver explicitly escapes
identifiers with backticks, and the sample test config includes Spanner enabled by default (not
disabledIfNotEnabledImplicitly). With the PR removing the prior enabledDrivers: ["postgres"]
restriction, this test becomes more likely to execute against drivers where "table" is not the
correct escape syntax.

test/github-issues/3837/issue-3837.test.ts[53-58]
src/driver/spanner/SpannerDriver.ts[315-317]
ormconfig.sample.json[130-140]

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 test constructs raw SQL using only MySQL backticks vs double quotes for everything else, which is not portable across drivers (e.g., Spanner uses backticks).

### Issue Context
The test suite can run against multiple drivers (see `ormconfig.sample.json`), and this PR removed the previous Postgres-only restriction.

### Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[53-60]
- test/github-issues/3837/issue-3837.test.ts[112-120]
- test/github-issues/3837/issue-3837.test.ts[185-192]
 - Replace hardcoded quoting with `datasource.driver.escape(&quot;tableOrColumn&quot;)` (and for ORDER BY, escape the column too), or use a TypeORM QueryBuilder SELECT to let the driver generate correct SQL.

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


3. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


View more (35)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


6. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


7. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


8. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


11. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


12. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


13. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


14. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


15. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


16. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


17. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


18. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 90a5c70 to 5823053 Compare March 1, 2026 15:11
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (58) 📘 Rule violations (16) 📎 Requirement gaps (0)

Grey Divider


Action required

1. values() needs mainAlias 🐞 Bug ✓ Correctness ⭐ New
Description
InsertQueryBuilder.values() now dereferences expressionMap.mainAlias and will throw if
.values() is called before .into(). This is a backwards-incompatible runtime regression for
fluent call orders that previously worked.
Code

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

+        this.derivedInsertColumns = undefined
+        if (
+            !this.expressionMap.mainAlias!.hasMetadata &&
+            !this.expressionMap.insertColumns.length
+        ) {
+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
Evidence
values() now assumes expressionMap.mainAlias is already initialized and accesses .hasMetadata,
but mainAlias is only set in .into(); QueryBuilder.insert() does not set it. Therefore
.insert().values(...).into(...) (or any .values() call before .into()) can crash before the
query is built.

src/query-builder/InsertQueryBuilder.ts[246-256]
src/query-builder/InsertQueryBuilder.ts[263-279]
src/query-builder/QueryBuilder.ts[201-210]

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

### Issue description
`InsertQueryBuilder.values()` dereferences `this.expressionMap.mainAlias!.hasMetadata`. If `values()` is invoked before `into()`, `mainAlias` can be undefined and will cause a runtime `TypeError`.

### Issue Context
`mainAlias` is initialized in `.into()`; `.insert()` alone does not set it.

### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[263-279]
- src/query-builder/InsertQueryBuilder.ts[246-256]
- src/query-builder/QueryBuilder.ts[201-210]

### Suggested change
- Replace `this.expressionMap.mainAlias!` usage in `values()` with a null-safe check:
 - `const mainAlias = this.expressionMap.mainAlias;`
 - Only derive columns if `mainAlias` exists and `!mainAlias.hasMetadata`.
- Keep existing fallback in `createColumnNamesExpression()`/`createValuesExpression()` so derived columns are still computed later when needed.

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (51)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


11. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


12. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


13. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


14. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


15. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


16. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


17. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


18. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
c...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 5823053 to 798ea48 Compare March 1, 2026 15:19
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (75) 📘 Rule violations (16) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


2. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (67)
4. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


5. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


6. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


7. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


10. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


11. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


12. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


13. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


14. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


15. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


16. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


17. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


18. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test f...

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (75) 📘 Rule violations (16) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Test fails on Spanner 🐞 Bug ⛯ Reliability ⭐ New
Description
The updated regression test no longer restricts enabledDrivers, so it will run on all configured
drivers, including Spanner in the default sample config. The test uses column types like
integer/varchar which Spanner won’t normalize and likely can’t create, causing the suite to fail
in environments where Spanner tests are enabled.
Code

test/github-issues/3837/issue-3837.test.ts[R16-36]

            (dataSources = await createTestingConnections({
                entities: [__dirname + "/entity/*{.js,.ts}"],
-                enabledDrivers: ["postgres"],
            })),
    )
    beforeEach(() => reloadTestingDatabases(dataSources))
    after(() => closeTestingConnections(dataSources))

-    xfail
-        .unless(() => dataSources.length > 0)
-        .it("should allow inserting named columns", () =>
-            Promise.all(
-                dataSources.map(async (connection) => {
-                    // Create the categories table.
-                    const qr = connection.createQueryRunner()
-                    await qr.createTable(
-                        new Table({
-                            name: "category",
-                            columns: [
-                                {
-                                    name: "id",
-                                    type: "int",
-                                    isPrimary: true,
-                                    isGenerated: true,
-                                    generationStrategy: "increment",
-                                },
-                                {
-                                    name: "name",
-                                    type: "varchar",
-                                },
-                            ],
-                        }),
-                    )
-
-                    const insert = connection.manager.insert("category", [
-                        { name: "Easy" },
-                        { name: "Medium" },
-                        { name: "Hard" },
+    it("should allow inserting named columns using manager.insert()", () =>
+        Promise.all(
+            dataSources.map(async (connection) => {
+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "integer",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
Evidence
When enabledDrivers is omitted, the test harness runs against every non-skipped driver in
ormconfig; ormconfig.sample.json includes Spanner with skip: false. The new test creates tables
with type: "integer"/"varchar". Spanner’s normalizeType returns unknown string types as-is, so
"integer" remains "integer" (not int64), which is not a Spanner supported type, making the table
creation (and thus the test) fail.

test/github-issues/3837/issue-3837.test.ts[14-18]
test/github-issues/3837/issue-3837.test.ts[28-41]
test/utils/test-utils.ts[236-254]
ormconfig.sample.json[130-140]
src/driver/spanner/SpannerDriver.ts[478-496]

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 regression test now runs across all configured drivers because `enabledDrivers` was removed. In the default configuration, Spanner is included and the test creates tables with `type: &quot;integer&quot;`/`&quot;varchar&quot;`, which Spanner does not normalize to supported types.

### Issue Context
`setupTestingConnections()` includes all drivers when `enabledDrivers` is omitted. `ormconfig.sample.json` includes Spanner with `skip: false`. Spanner `normalizeType()` returns unknown string types unchanged.

### Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[14-18]
- test/github-issues/3837/issue-3837.test.ts[28-41]

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (68)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


11. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


12. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


13. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


14. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


15. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


16. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


17. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
[src/query-builder/Inser...

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (91) 📘 Rule violations (16) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Stale derived columns cache 🐞 Bug ✓ Correctness ⭐ New
Description
derivedInsertColumns is computed once inside values() for metadata-less inserts and then preferred
later when building SQL. Because valuesSet is stored by reference and can be mutated after calling
.values() (or after calling execute() but before the query string is generated), the cached
derivedInsertColumns can diverge from the actual valueSets used, leading to ignored newly-added
columns or incorrect column/value alignment.
Code

src/query-builder/InsertQueryBuilder.ts[R269-278]

+        this.derivedInsertColumns = undefined
+        if (
+            !this.expressionMap.mainAlias?.hasMetadata &&
+            !this.expressionMap.insertColumns.length
+        ) {
+            const valueSets = Array.isArray(values) ? values : [values]
+            this.derivedInsertColumns = this.getColumnNamesFromValueSets(
+                valueSets as any,
+            )
+        }
Evidence
InsertQueryBuilder stores the caller-provided values by reference and eagerly caches
derivedInsertColumns from that snapshot in values(). Later SQL generation prefers the cached list
over recomputing from the current getValueSets(), so any post-.values() mutation (e.g., pushing a
new row with an extra column) will not be reflected in the emitted column list or value ordering.

src/query-builder/InsertQueryBuilder.ts[263-280]
src/query-builder/InsertQueryBuilder.ts[951-957]
src/query-builder/InsertQueryBuilder.ts[858-867]

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

### Issue description
`derivedInsertColumns` is computed once in `values()` and later preferred when generating SQL. Since `valuesSet` is stored by reference, callers can mutate the values array/object after calling `.values()` (or after calling `.execute()` but before SQL generation runs). This can make `derivedInsertColumns` stale, causing newly-added columns/rows to be omitted or column/value alignment to be incorrect.

### Issue Context
- `values()` assigns `this.expressionMap.valuesSet = values` (no clone).
- `derivedInsertColumns` is computed in `values()` and later used via `this.derivedInsertColumns || ...`.

### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[263-280]
- src/query-builder/InsertQueryBuilder.ts[851-877]
- src/query-builder/InsertQueryBuilder.ts[920-1044]

### Suggested direction
- Remove the eager computation in `values()` and compute column names from `this.getValueSets()` when building the query.
- Option A (simplest): stop using `derivedInsertColumns` entirely and always call `getColumnNamesFromValueSets(valueSets)` in both places.
- Option B: set `this.derivedInsertColumns = this.getColumnNamesFromValueSets(this.getValueSets())` inside `createInsertExpression()` (or at the start of `createValuesExpression()`), so it reflects the latest values and stays consistent for the current query build.

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


2. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                       expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


3. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

   beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;quot;postgres&amp;quot;]` to include additional databases like `[&amp;quot;postgres&amp;quot;, &amp;quot;mysql&amp;quot;, &amp;quot;sqlite&amp;quot;]` or remove the restriction entirely to test on all available drivers

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


View more (84)
4. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


5. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;#x27;A&amp;amp;#x27;, age: 20}, {name: &amp;amp;#x27;B&amp;amp;#x27;}]` where the second row is missing the &amp;amp;#x27;age&amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;#x27;name&amp;amp;#x27;, &amp;amp;#x27;description&amp;amp;#x27;, &amp;amp;#x27;priority&amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


6. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)

           valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                   if (columnIndex === 0) {
                       expression += "("
                   }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;#x27;t&amp;#x27;, [&amp;#x27;a&amp;#x27;,&amp;#x27;b&amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


7. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


8. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


9. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


10. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


11. Leaked QueryRunner in tests 🐞 Bug ⛯ Reliability
Description
The new regression tests create QueryRunner instances but never call release(), which can leak
pooled connections and make the test suite flaky/hang under limited pool sizes.
Code

test/github-issues/3837/issue-3837.test.ts[R27-45]

+                const qr = connection.createQueryRunner()
+                await qr.createTable(
+                    new Table({
+                        name: "category",
+                        columns: [
+                            {
+                                name: "id",
+                                type: "int",
+                                isPrimary: true,
+                                isGenerated: true,
+                                generationStrategy: "increment",
+                            },
+                            {
+                                name: "name",
+                                type: "varchar",
+                            },
+                        ],
+                    }),
+                )
Evidence
The new tests create a QueryRunner and use it to create tables, but there is no corresponding `await
qr.release()` anywhere in the file. TypeORM’s QueryRunner contract explicitly requires releasing the
used database connection, and other tests follow this pattern.

test/github-issues/3837/issue-3837.test.ts[23-55]
test/github-issues/3837/issue-3837.test.ts[57-80]
test/github-issues/3837/issue-3837.test.ts[109-143]
src/query-runner/QueryRunner.ts[83-87]
test/functional/query-runner/create-index.test.ts[86-92]

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

## Issue description
New tests in `issue-3837.test.ts` create `QueryRunner` instances via `connection.createQueryRunner()` but never release them. This can leak pooled connections and lead to flaky/hanging test runs.
## Issue Context
`QueryRunner.release()` is responsible for returning the database connection to the pool. Other tests release their query runners explicitly.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[23-55]
- test/github-issues/3837/issue-3837.test.ts[57-80]
- test/github-issues/3837/issue-3837.test.ts[109-143]
## Suggested change
Wrap each `createQueryRunner()` usage in `try/finally`, e.g.:

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


12. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                      expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or documentation warning about the limitation
- test/github-issues/3837/issue-3837.test.ts[109-183] - Add test case with NOT NULL columns to validate the fix

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


13. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

  beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;quot;postgres&amp;amp;quot;]` to include additional databases like `[&amp;amp;quot;postgres&amp;amp;quot;, &amp;amp;quot;mysql&amp;amp;quot;, &amp;amp;quot;sqlite&amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


14. Insufficient Test Coverage Across Database Drivers 🐞 Bug ⛯ Reliability
Description
• The test file restricts testing to PostgreSQL only (enabledDrivers: ["postgres"]), but the code
changes affect all database drivers • The getColumnNamesFromValueSets method is used in
database-agnostic code paths that execute for all drivers • Different databases handle NULL/DEFAULT
values differently (Oracle, SQLite, SAP, Spanner have specific branches at lines 953-965) • Without
testing on multiple databases, database-specific bugs in the column merging logic may go undetected
Code

test/github-issues/3837/issue-3837.test.ts[1]

 beforeEach(() => reloadTestingDatabases(connections))
Evidence
The test configuration explicitly limits testing to PostgreSQL, while the implementation code in
InsertQueryBuilder.ts contains database-specific logic for handling undefined values. The
createValuesExpression method has conditional branches for Oracle, SQLite, SAP, and Spanner that
determine whether to use NULL or DEFAULT for missing columns. These database-specific behaviors are
not validated by the current test suite.

test/github-issues/3837/issue-3837.test.ts[15-17]
src/query-builder/InsertQueryBuilder.ts[952-965]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test for bulk inserts with heterogeneous column sets only runs on PostgreSQL, but the implementation affects all database drivers. Different databases handle NULL/DEFAULT values differently, and this needs to be validated.
## Issue Context
The `getColumnNamesFromValueSets` method is used in `createValuesExpression` which has database-specific branches for Oracle, SQLite, SAP, and Spanner. These branches determine whether to use NULL or DEFAULT for undefined column values.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[15-17] - Change `enabledDrivers: [&amp;amp;amp;quot;postgres&amp;amp;amp;quot;]` to include additional databases like `[&amp;amp;amp;quot;postgres&amp;amp;amp;quot;, &amp;amp;amp;quot;mysql&amp;amp;amp;quot;, &amp;amp;amp;quot;sqlite&amp;amp;amp;quot;]` or remove the restriction entirely to test on all available drivers

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


15. Missing test for heterogeneous value sets 🐞 Bug ⛯ Reliability
Description
• The PR changes column extraction from using only the first value set to merging columns from all
value sets via getColumnNamesFromValueSets() • Test cases only verify homogeneous data where all
rows have identical keys • The core functionality (handling rows with different column sets) remains
untested, risking silent regression
Code

test/github-issues/3837/issue-3837.test.ts[R81-85]

+                const data = [
+                    { type: "Easy" },
+                    { type: "Medium" },
+                    { type: "Hard" },
+                ]
Evidence
Both test cases use homogeneous value sets where every row has identical keys. The first test (lines
47-51) inserts three rows each with only 'name' property. The second test (lines 81-85) inserts
three rows each with only 'type' property. The new getColumnNamesFromValueSets method is designed to
merge columns from multiple rows with different keys (e.g., [{name: 'A', age: 20}, {name: 'B'}]),
but this critical scenario is never tested.

test/github-issues/3837/issue-3837.test.ts[47-51]
test/github-issues/3837/issue-3837.test.ts[81-85]
src/query-builder/InsertQueryBuilder.ts[1001-1013]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The test suite doesn&amp;amp;amp;#x27;t verify the core functionality of the PR: handling bulk inserts where different rows have different column sets. This leaves the main bug fix untested.
## Issue Context
The PR changes the column extraction logic from using only the first value set (`valueSets.length === 1`) to merging columns from all value sets. The new `getColumnNamesFromValueSets` method is designed to handle cases like `[{name: &amp;amp;amp;#x27;A&amp;amp;amp;#x27;, age: 20}, {name: &amp;amp;amp;#x27;B&amp;amp;amp;#x27;}]` where the second row is missing the &amp;amp;amp;#x27;age&amp;amp;amp;#x27; column.
## Fix Focus Areas
- test/github-issues/3837/issue-3837.test.ts[108-108]
Add a third test case after line 107 that:
1. Creates a table with multiple nullable columns (e.g., &amp;amp;amp;#x27;name&amp;amp;amp;#x27;, &amp;amp;amp;#x27;description&amp;amp;amp;#x27;, &amp;amp;amp;#x27;priority&amp;amp;amp;#x27;)
2. Inserts multiple rows where each row has a different subset of columns
3. Verifies all rows were inserted correctly with DEFAULT/NULL for missing columns

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


16. Explicit columns order mismatch 🐞 Bug ✓ Correctness
Description
For metadata-less inserts using .into(table, columns), the INSERT column list uses
expressionMap.insertColumns, but the VALUES tuple order is derived from keys in the provided value
objects. If object key order differs from the explicit column list (or objects include extra keys),
inserts can silently swap values between columns or generate SQL with mismatched column/value
counts.
Code

src/query-builder/InsertQueryBuilder.ts[R937-943]

+            const columnNames = this.getColumnNamesFromValueSets(valueSets)
          valueSets.forEach((valueSet, insertionIndex) => {
-                const columns = Object.keys(valueSet)
-                columns.forEach((columnName, columnIndex) => {
+                columnNames.forEach((columnName, columnIndex) => {
                  if (columnIndex === 0) {
                      expression += "("
                  }
Evidence
.into() stores the explicit column list in expressionMap.insertColumns, and
createColumnNamesExpression() will emit that list. But in the metadata-less VALUES generation
path, the code ignores insertColumns and iterates over a derived columnNames list from the value
sets, which may not match the explicit list order/content. This can misalign VALUES with the emitted
column list.

src/query-builder/InsertQueryBuilder.ts[241-252]
src/query-builder/InsertQueryBuilder.ts[836-860]
src/query-builder/InsertQueryBuilder.ts[933-988]

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

## Issue description
For metadata-less inserts with explicit columns (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;])`), the query’s column list is emitted from `expressionMap.insertColumns`, but the VALUES tuple order is derived from keys found in the value objects. This can misalign column/value ordering or include extra columns not present in the emitted column list.
### Issue Context
- `.into()` sets `expressionMap.insertColumns`.
- `createColumnNamesExpression()` emits `insertColumns` when provided.
- `createValuesExpression()` (metadata-less path) currently derives `columnNames` from value sets and does not consider `insertColumns`.
### Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[933-988]
- src/query-builder/InsertQueryBuilder.ts[836-860]
### Proposed change (high level)
- In the `columns.length === 0` branch of `createValuesExpression()`, set:
- `const columnNames = this.expressionMap.insertColumns.length ? this.expressionMap.insertColumns : this.getColumnNamesFromValueSets(valueSets)`
- Ensure any keys in `valueSet` that are not in `insertColumns` are ignored implicitly by iterating `columnNames`.
- Add/adjust a regression test where `insertColumns` order differs from the insertion-order of keys in the value objects (e.g. `.into(&amp;amp;#x27;t&amp;amp;#x27;, [&amp;amp;#x27;a&amp;amp;#x27;,&amp;amp;#x27;b&amp;amp;#x27;]).values([{ b: 2, a: 1 }])`) and assert correct column/value mapping.

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


17. Missing NOT NULL constraint validation 🐞 Bug ⛯ Reliability
Description
• When inserting rows with different column sets, missing columns are automatically filled with NULL
or DEFAULT (lines 952-965), but there's no validation that these columns are nullable • For columns
with NOT NULL constraints and no default value, this will cause SQL errors at runtime • The test
only validates nullable columns (lines 125-139), missing the critical case of NOT NULL columns •
This breaks the feature for common schema patterns where some columns are required
Code

src/query-builder/InsertQueryBuilder.ts[1]

                     expression += this.createParameter(value)
Evidence
The code path for tables without metadata (lines 934-988) handles undefined values by inserting NULL
or DEFAULT based on the database driver. However, unlike the metadata path (lines 870-932) which has
access to column metadata including nullability constraints, the non-metadata path has no way to
validate if a column can accept NULL. The test case only validates the happy path with all nullable
columns (lines 125-139 show isNullable: true for all columns). The comment at line 1365 in the
metadata path even acknowledges this risk: 'otherwise simply use NULL and pray if column is
nullable'.

src/query-builder/InsertQueryBuilder.ts[952-965]
test/github-issues/3837/issue-3837.test.ts[125-139]
src/query-builder/InsertQueryBuilder.ts[1365-1365]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue Description
The bulk insert feature for tables without metadata fills missing columns with NULL/DEFAULT without validating column constraints. This causes runtime SQL errors when inserting rows with different column sets if any omitted column has a NOT NULL constraint without a default value.
## Issue Context
When processing bulk inserts for tables without metadata (lines 934-988), the code uses `getColumnNamesFromValueSets()` to collect all columns across all value objects, then fills missing values with NULL or DEFAULT. Unlike the metadata path (lines 870-932), there&amp;amp;amp;#x27;s no access to column constraints to validate if NULL is acceptable.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[1008-1023] - Consider adding a parameter to require explicit column specification when using heterogeneous inserts
- src/query-builder/InsertQueryBuilder.ts[843-854] - Add validation or ...

@Cprakhar
Cprakhar force-pushed the fix/metadata-less-insert-columns branch from 798ea48 to a090db4 Compare March 15, 2026 17:07
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Persistent review updated to latest commit a090db4

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit fb3b9bf

@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

Manager insert query with auto-generated columns

5 participants