Skip to content

fix: query stack trace - #12056

Merged
alumni merged 2 commits into
typeorm:masterfrom
Cprakhar:fix-mysql-stack-trace
Apr 24, 2026
Merged

alumni merged 2 commits into
typeorm:masterfrom
Cprakhar:fix-mysql-stack-trace

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Feb 28, 2026 •

Copy link
Copy Markdown
Collaborator

Description of change

This PR continues the work from #11273

Closes #11499
Closes #11765

Changes

  • mysql2 package supports promise via .promise() method
  • removed new Promise() from the query in mssql

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11765 #11499
  • 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)

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

Copy link
Copy Markdown

User description

Description of change

This PR continues the work from #11273

Closes #11499
Closes #11765

Changes

  • replaced Promise wrapper in query method of SqlServerQueryRunner and MysqlQueryRunner
  • Implemented a promisifyMethod in the ObjectUtils.ts

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11765 #11499
  • 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)

PR Type

Bug fix, Enhancement


Description

  • Refactored MySQL and SQL Server query runners to preserve caller stack traces

  • Implemented promisifyMethod utility to replace Promise wrappers cleanly

  • Moved error construction outside callback scope for accurate stack traces

  • Added comprehensive tests for stack trace preservation in query errors


Diagram Walkthrough

flowchart LR
  A["Query Runners<br/>MySQL/SqlServer"] -->|"Replace Promise<br/>wrapper"| B["promisifyMethod<br/>utility"]
  B -->|"Preserve caller<br/>stack trace"| C["Error with<br/>call site info"]
  A -->|"Move error<br/>construction"| C
  D["Test Suite"] -->|"Verify stack<br/>traces"| C
Loading

File Walkthrough

Relevant files
Bug fix
MysqlQueryRunner.ts
Refactor MySQL query method for stack trace preservation 

src/driver/mysql/MysqlQueryRunner.ts

  • Replaced Promise wrapper with ObjectUtils.promisifyMethod for cleaner
    async handling
  • Moved query configuration and error handling outside callback scope
  • Preserved caller stack trace by constructing errors at call site
  • Simplified control flow using try-catch-finally instead of nested
    callbacks
+77/-81 
SqlServerQueryRunner.ts
Refactor SQL Server query method for stack trace preservation

src/driver/sqlserver/SqlServerQueryRunner.ts

  • Replaced Promise wrapper with ObjectUtils.promisifyMethod call
  • Moved query execution timing and logging outside callback scope
  • Ensured QueryFailedError is thrown with proper parameters
  • Consolidated import statements for cleaner code organization
+33/-38 
Enhancement
ObjectUtils.ts
Add promisifyMethod utility for callback conversion           

src/util/ObjectUtils.ts

  • Added new promisifyMethod static method to convert callback-based
    methods to Promises
  • Generic implementation accepts object, method name, and variable
    arguments
  • Handles error-first callback pattern with proper error rejection
  • Enables consistent async/await usage across query runners
+19/-0   
Tests
hygge.ts
Add test entity for stack trace validation                             

test/github-issues/11271/entity/hygge.ts

  • Created test entity Hygge with id and description columns
  • Used for testing query error scenarios with entity operations
+12/-0   
issue-11271.test.ts
Add stack trace preservation tests for query runners         

test/github-issues/11271/issue-11271.test.ts

  • Added test suite for stack trace preservation in MySQL and MSSQL
    drivers
  • Tests verify that error stack traces include the calling function name
  • Covers both raw query execution and entity repository operations
  • Validates stack trace includes my_named_function_123 and
    my_named_function_1234
+77/-0   

@pkg-pr-new

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

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

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

commit: 65a51fb

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 428fff5

CategorySuggestion                                                                                                                                    Impact
General
Make own-property check robust

Replace raw?.hasOwnProperty("affectedRows") with
Object.prototype.hasOwnProperty.call(raw, "affectedRows") for a safer property
check.

src/driver/mysql/MysqlQueryRunner.ts [251-253]

-if (raw?.hasOwnProperty("affectedRows")) {
+if (raw && Object.prototype.hasOwnProperty.call(raw, "affectedRows")) {
     result.affected = raw.affectedRows
 }
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion provides a more robust way to check for property existence, preventing potential edge-case errors, which is a good practice for library code.

Low
  • Update

Previous suggestions

✅ Suggestions up to commit 12fbee5
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Handle early failures consistently
Suggestion Impact:The commit moved maxQueryExecutionTime and queryStartTime initialization outside the inner query execution flow and added catch logic that computes queryExecutionTime (when available) and logs slow queries in the error path, improving consistency of failure handling. It also refactored the request.query callback to a promisified call with uniform QueryFailedError wrapping.

code diff:

@@ -217,6 +217,8 @@
         await this.broadcaster.broadcast("BeforeQuery", query, parameters)
 
         const broadcasterResult = new BroadcasterResult()
+        const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime
+        let queryStartTime: number | undefined
 
         try {
             const pool = await (this.mode === "slave"
@@ -245,45 +247,39 @@
                     }
                 })
             }
-            const queryStartTime = Date.now()
-
-            const raw = await new Promise<any>((ok, fail) => {
-                request.query(query, (err: any, raw: any) => {
-                    // log slow queries if maxQueryExecution time is set
-                    const maxQueryExecutionTime =
-                        this.driver.options.maxQueryExecutionTime
-                    const queryEndTime = Date.now()
-                    const queryExecutionTime = queryEndTime - queryStartTime
-
-                    this.broadcaster.broadcastAfterQueryEvent(
-                        broadcasterResult,
-                        query,
-                        parameters,
-                        true,
-                        queryExecutionTime,
-                        raw,
-                        undefined,
-                    )
-
-                    if (
-                        maxQueryExecutionTime &&
-                        queryExecutionTime > maxQueryExecutionTime
-                    ) {
-                        this.driver.connection.logger.logQuerySlow(
-                            queryExecutionTime,
-                            query,
-                            parameters,
-                            this,
-                        )
-                    }
-
-                    if (err) {
-                        fail(new QueryFailedError(query, parameters, err))
-                    }
-
-                    ok(raw)
-                })
+            queryStartTime = Date.now()
+
+            const raw = await ObjectUtils.promisifyMethod(
+                request,
+                "query",
+                query,
+            ).catch((err) => {
+                throw new QueryFailedError(query, parameters, err)
             })
+            // log slow queries if maxQueryExecution time is set
+            const queryExecutionTime = Date.now() - queryStartTime
+
+            this.broadcaster.broadcastAfterQueryEvent(
+                broadcasterResult,
+                query,
+                parameters,
+                true,
+                queryExecutionTime,
+                raw,
+                undefined,
+            )
+
+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime > maxQueryExecutionTime
+            ) {
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
+            }
 
             const result = new QueryResult()
 
@@ -305,12 +301,25 @@
                     result.raw = raw.recordset
             }
 
-            if (useStructuredResult) {
-                return result
-            } else {
-                return result.raw
+            return useStructuredResult ? result : result.raw
+        } catch (err) {
+            const queryExecutionTime = queryStartTime
+                ? Date.now() - queryStartTime
+                : undefined
+
+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime !== undefined &&
+                queryExecutionTime > maxQueryExecutionTime
+            ) {
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
             }
-        } catch (err) {
+
             this.driver.connection.logger.logQueryError(
                 err,
                 query,

Refactor the query method to ensure consistent error handling for all failure
modes, including connection acquisition. Move logging and broadcasterResult
initialization before the main try block and use a single try/catch/finally to
handle all errors uniformly.

src/driver/sqlserver/SqlServerQueryRunner.ts [216-351]

+const broadcasterResult = new BroadcasterResult()
+const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime
+let queryStartTime: number | undefined
+
+this.driver.connection.logger.logQuery(query, parameters, this)
+await this.broadcaster.broadcast("BeforeQuery", query, parameters)
+
 try {
     const pool = await (this.mode === "slave"
         ? this.driver.obtainSlaveConnection()
         : this.driver.obtainMasterConnection())
 
-    this.driver.connection.logger.logQuery(query, parameters, this)
-    await this.broadcaster.broadcast("BeforeQuery", query, parameters)
+    const request = new this.driver.mssql.Request(
+        this.isTransactionActive ? this.databaseConnection : pool,
+    )
+    ...
+} catch (err) {
+    const queryExecutionTime =
+        queryStartTime !== undefined
+            ? Date.now() - queryStartTime
+            : undefined
 
-    const broadcasterResult = new BroadcasterResult()
-    const maxQueryExecutionTime =
-        this.driver.options.maxQueryExecutionTime
-    let queryStartTime: number | undefined
+    if (
+        maxQueryExecutionTime &&
+        queryExecutionTime !== undefined &&
+        queryExecutionTime > maxQueryExecutionTime
+    )
+        this.driver.connection.logger.logQuerySlow(
+            queryExecutionTime,
+            query,
+            parameters,
+            this,
+        )
 
-    try {
-        const request = new this.driver.mssql.Request(
-            this.isTransactionActive ? this.databaseConnection : pool,
-        )
-        ...
-    } catch (err) {
-        ...
-        throw new QueryFailedError(query, parameters, err)
-    } finally {
-        await broadcasterResult.wait()
-    }
+    this.driver.connection.logger.logQueryError(err, query, parameters, this)
+    this.broadcaster.broadcastAfterQueryEvent(
+        broadcasterResult,
+        query,
+        parameters,
+        false,
+        queryExecutionTime,
+        undefined,
+        err,
+    )
+    throw new QueryFailedError(query, parameters, err)
 } finally {
-    release()
+    await broadcasterResult.wait()
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a flaw in the error handling logic where failures during connection acquisition are not logged or handled consistently with other query errors, which is a valid and important point for robust error management.

Medium
Preserve multi-argument callback results

Update promisifyMethod to handle callbacks that provide multiple result
arguments. The promise should resolve with an array of results in such cases,
rather than just the first result.

src/util/ObjectUtils.ts [86-115]

 static promisifyMethod<T = any>(
     obj: any,
     method: string,
     ...args: any[]
 ): Promise<T> {
     return new Promise<T>((resolve, reject) => {
         const fn = obj?.[method]
         if (typeof fn !== "function") {
-            return reject(
-                new Error(`Object does not have method ${method}`),
-            )
+            return reject(new Error(`Object does not have method "${method}"`))
         }
 
         try {
             fn.call(
                 obj,
                 ...args,
-                (err: Error | null | undefined, result?: T) => {
-                    if (err) {
-                        reject(err)
-                    } else {
-                        resolve(result as T)
-                    }
+                (err: any, ...results: any[]) => {
+                    if (err) return reject(err)
+                    resolve((results.length <= 1 ? results[0] : results) as T)
                 },
             )
         } catch (err) {
             reject(err)
         }
     })
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that the new promisifyMethod utility only handles the first result argument from a callback, which is a limitation. While the current usage in the PR doesn't require multiple arguments, improving the utility for future use is a good practice.

Low
Suggestions up to commit 1e87074
CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve multi-argument callback results

Refactor promisifyMethod to handle callbacks with multiple result arguments and
prevent promises from being settled more than once.

src/util/ObjectUtils.ts [86-115]

 static promisifyMethod<T = any>(
     obj: any,
     method: string,
     ...args: any[]
 ): Promise<T> {
     return new Promise<T>((resolve, reject) => {
         const fn = obj?.[method]
         if (typeof fn !== "function") {
             return reject(
-                new Error(`Object does not have method ${method}`),
+                new Error(`Object does not have method "${method}"`),
             )
+        }
+
+        let settled = false
+        const onceResolve = (value: T) => {
+            if (settled) return
+            settled = true
+            resolve(value)
+        }
+        const onceReject = (err: any) => {
+            if (settled) return
+            settled = true
+            reject(err)
         }
 
         try {
             fn.call(
                 obj,
                 ...args,
-                (err: Error | null | undefined, result?: T) => {
-                    if (err) {
-                        reject(err)
-                    } else {
-                        resolve(result as T)
-                    }
+                (err: Error | null | undefined, ...results: any[]) => {
+                    if (err) return onceReject(err)
+                    // Preserve all callback results when present; otherwise return the single value.
+                    onceResolve((results.length <= 1 ? results[0] : results) as T)
                 },
             )
         } catch (err) {
-            reject(err)
+            onceReject(err)
         }
     })
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that promisifyMethod might drop extra callback arguments, and proposes a more robust implementation that also prevents double-settling of promises, which is a good practice for a generic utility function.

Medium
General
Use safe own-property checks

Replace raw?.hasOwnProperty("affectedRows") with the safer
Object.prototype.hasOwnProperty.call(raw, "affectedRows") to prevent potential
issues with overridden properties.

src/driver/mysql/MysqlQueryRunner.ts [251-253]

-if (raw?.hasOwnProperty("affectedRows")) {
+if (Object.prototype.hasOwnProperty.call(raw, "affectedRows")) {
     result.affected = raw.affectedRows
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion provides a more robust way to check for property existence, which is a good practice, although the risk of hasOwnProperty being overridden on a database result object is low.

Low
✅ Suggestions up to commit 509df80
CategorySuggestion                                                                                                                                    Impact
General
Preserve timing data on errors

In the catch block of the query method, pass the calculated queryExecutionTime
to broadcastAfterQueryEvent instead of undefined to provide consistent timing
data on errors.

src/driver/mysql/MysqlQueryRunner.ts [256-288]

 } catch (err) {
     const queryExecutionTime = Date.now() - queryStartTime
 
     if (
         maxQueryExecutionTime &&
         queryExecutionTime > maxQueryExecutionTime
     )
         this.driver.connection.logger.logQuerySlow(
             queryExecutionTime,
             query,
             parameters,
             this,
         )
 
     this.driver.connection.logger.logQueryError(
         err,
         query,
         parameters,
         this,
     )
     this.broadcaster.broadcastAfterQueryEvent(
         broadcasterResult,
         query,
         parameters,
         false,
-        undefined,
+        queryExecutionTime,
         undefined,
         err,
     )
     throw new QueryFailedError(query, parameters, err)
 } finally {
     await broadcasterResult.wait()
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that queryExecutionTime is available on error but is not passed to the event broadcaster, which is inconsistent with the success path and a missed opportunity for better diagnostics.

Medium
Possible issue
✅ Prevent calling missing methods
Suggestion Impact:The commit added an early return when the method is missing by changing the branch to `return reject(new Error(...))`, preventing execution of `fn.call` on a non-function.

code diff:

+            const fn = obj?.[method]
+            if (typeof fn !== "function") {
+                return reject(
+                    new Error(`Object does not have method ${method}`),
+                )
+            }

In the new promisifyMethod, add a return after rejecting the promise for a
non-existent method to prevent further execution and a subsequent TypeError.

src/util/ObjectUtils.ts [86-114]

 static promisifyMethod<T = any>(
     obj: any,
     method: string,
     ...args: any[]
 ): Promise<T> {
     return new Promise<T>((resolve, reject) => {
         const fn = obj?.[method]
         if (typeof fn !== "function") {
             reject(new Error(`Object does not have method ${method}`))
+            return
         }
 
         try {
             fn.call(
                 obj,
                 ...args,
                 (err: Error | null | undefined, result?: T) => {
                     if (err) {
                         reject(err)
                     } else {
                         resolve(result as T)
                     }
                 },
             )
         } catch (err) {
             reject(err)
         }
     })
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a bug in the new promisifyMethod where execution continues after rejection, which would cause a TypeError and a second, less-informative rejection.

Low
Suggestions
CategorySuggestion                                                                                                                                    Impact
Possible issue
Reject promise on sync failures

Wrap the method invocation inside promisifyMethod with a try...catch block and
add a check to ensure the method is a function. This prevents synchronous errors
from causing unhandled exceptions by converting them into promise rejections.

src/util/ObjectUtils.ts [86-103]

 static promisifyMethod<T = any>(
     obj: any,
     method: string,
     ...args: any[]
 ): Promise<T> {
     return new Promise<T>((resolve, reject) => {
-        obj[method](
-            ...args,
-            (err: Error | null | undefined, result?: T) => {
-                if (err) {
-                    reject(err)
-                } else {
-                    resolve(result as T)
-                }
-            },
-        )
+        const fn = obj?.[method]
+        if (typeof fn !== "function") {
+            return reject(
+                new TypeError(`Object method "${method}" is not a function`),
+            )
+        }
+
+        try {
+            fn.call(
+                obj,
+                ...args,
+                (err: Error | null | undefined, result?: T) => {
+                    if (err) {
+                        reject(err)
+                    } else {
+                        resolve(result as T)
+                    }
+                },
+            )
+        } catch (e) {
+            reject(e)
+        }
     })
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that synchronous errors inside the Promise constructor of promisifyMethod would cause unhandled exceptions, and the proposed try...catch block is the correct way to fix this potential crash.

Medium
✅ Prevent incorrect slow-query logging
Suggestion Impact:The commit changes queryStartTime to be undefined initially, sets it only right before executing the query, and in the catch block computes queryExecutionTime only if queryStartTime was set and gates slow-query logging on that, preventing incorrect slow-query logging on pre-start errors.

code diff:

@@ -217,7 +217,8 @@
         await this.broadcaster.broadcast("BeforeQuery", query, parameters)
 
         const broadcasterResult = new BroadcasterResult()
-
+        const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime
+        let queryStartTime: number | undefined
         try {
             const pool = await (this.mode === "slave"
                 ? this.driver.obtainSlaveConnection()
@@ -245,45 +246,39 @@
                     }
                 })
             }
-            const queryStartTime = Date.now()
-
-            const raw = await new Promise<any>((ok, fail) => {
-                request.query(query, (err: any, raw: any) => {
-                    // log slow queries if maxQueryExecution time is set
-                    const maxQueryExecutionTime =
-                        this.driver.options.maxQueryExecutionTime
-                    const queryEndTime = Date.now()
-                    const queryExecutionTime = queryEndTime - queryStartTime
-
-                    this.broadcaster.broadcastAfterQueryEvent(
-                        broadcasterResult,
-                        query,
-                        parameters,
-                        true,
-                        queryExecutionTime,
-                        raw,
-                        undefined,
-                    )
-
-                    if (
-                        maxQueryExecutionTime &&
-                        queryExecutionTime > maxQueryExecutionTime
-                    ) {
-                        this.driver.connection.logger.logQuerySlow(
-                            queryExecutionTime,
-                            query,
-                            parameters,
-                            this,
-                        )
-                    }
-
-                    if (err) {
-                        fail(new QueryFailedError(query, parameters, err))
-                    }
-
-                    ok(raw)
-                })
-            })
+
+            queryStartTime = Date.now()
+
+            const raw = await ObjectUtils.promisifyMethod(
+                request,
+                "query",
+                query,
+            )
+            // log slow queries if maxQueryExecution time is set
+            const queryEndTime = Date.now()
+            const queryExecutionTime = queryEndTime - queryStartTime
+
+            this.broadcaster.broadcastAfterQueryEvent(
+                broadcasterResult,
+                query,
+                parameters,
+                true,
+                queryExecutionTime,
+                raw,
+                undefined,
+            )
+
+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime > maxQueryExecutionTime
+            ) {
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
+            }
 
             const result = new QueryResult()
 
@@ -311,6 +306,23 @@
                 return result.raw
             }
         } catch (err) {
+            const queryExecutionTime =
+                queryStartTime !== undefined
+                    ? Date.now() - queryStartTime
+                    : undefined
+
+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime !== undefined &&
+                queryExecutionTime > maxQueryExecutionTime
+            )
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
+

In SqlServerQueryRunner.ts, initialize queryStartTime to undefined and only
calculate queryExecutionTime and log slow queries if queryStartTime has been
set. This prevents incorrect slow-query logging when an error occurs before the
query starts.

src/driver/sqlserver/SqlServerQueryRunner.ts [220-320]

 const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime
-let queryStartTime: number = 0
+let queryStartTime: number | undefined
 try {
     const pool = await (this.mode === "slave"
         ? this.driver.obtainSlaveConnection()
         : this.driver.obtainMasterConnection())
     const request = new this.driver.mssql.Request(
 ...
     queryStartTime = Date.now()
 ...
 } catch (err) {
-    const queryExecutionTime = Date.now() - queryStartTime
+    const queryExecutionTime =
+        queryStartTime !== undefined ? Date.now() - queryStartTime : undefined
 
     if (
+        queryExecutionTime !== undefined &&
         maxQueryExecutionTime &&
         queryExecutionTime > maxQueryExecutionTime
-    )
+    ) {
         this.driver.connection.logger.logQuerySlow(
             queryExecutionTime,
             query,
             parameters,
             this,
         )
+    }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a logic flaw where an error before queryStartTime is set would lead to incorrect slow-query logging. The fix is valid and improves the robustness of the error handling logic.

Medium

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Assumes mysql2 promise API 🐞 Bug ☼ Reliability ⭐ New
Description
MysqlQueryRunner.query now unconditionally calls databaseConnection.promise().query(...), which
will throw a runtime TypeError if the configured MySQL options.driver returns connections
without a .promise() method. This is a breaking change for the documented extension point
MysqlDataSourceOptions.driver that previously worked with callback-only drivers.
Code

src/driver/mysql/MysqlQueryRunner.ts[R219-223]

+        try {
+            const [raw] = await databaseConnection
+                .promise()
+                .query(queryPayload, parameters)

-                        if (err) {
-                            this.driver.dataSource.logger.logQueryError(
-                                err,
-                                query,
-                                parameters,
-                                this,
-                            )
-                            this.broadcaster.broadcastAfterQueryEvent(
-                                broadcasterResult,
-                                query,
-                                parameters,
-                                false,
-                                undefined,
-                                undefined,
-                                err,
-                            )
Evidence
The new implementation uses .promise() on the acquired connection. The MySQL driver can be
overridden via MysqlDataSourceOptions.driver and is assigned without validating that the provided
driver/connection supports mysql2's promise wrapper API, so a callback-only driver will now fail at
runtime when .promise() is invoked.

src/driver/mysql/MysqlQueryRunner.ts[198-295]
src/driver/mysql/MysqlDataSourceOptions.ts[10-22]
src/driver/mysql/MysqlDriver.ts[1142-1151]

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

### Issue description
`MysqlQueryRunner.query()` now requires `databaseConnection.promise()` to exist. If users pass a custom MySQL driver via `MysqlDataSourceOptions.driver` (or otherwise provide a connection object without a `.promise()` method), all queries will fail at runtime.

### Issue Context
TypeORM exposes a `driver?: any` override for MySQL. The current code path assumes mysql2's callback connection shape plus its `.promise()` wrapper.

### Fix approach
Implement a safe fallback:
- If `typeof databaseConnection.promise === "function"`, keep the new promise-based path.
- Otherwise, fall back to the callback-based `databaseConnection.query(...)` implementation (similar to the previous code) or throw a clear, actionable error stating that the provided driver must be mysql2-compatible and expose `.promise()`.

### Fix Focus Areas
- src/driver/mysql/MysqlQueryRunner.ts[198-295]
- src/driver/mysql/MysqlDataSourceOptions.ts[10-22]
- src/driver/mysql/MysqlDriver.ts[1142-1151]

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


2. Issue tests added under test/github-issues 📘 Rule violation ⚙ Maintainability
Description
New tests for this issue were added under test/github-issues/11271 instead of the functional test
suite. This violates the requirement to keep issue fixes in test/functional unless there is a
clear documented reason.
Code

test/github-issues/11271/issue-11271.test.ts[R1-76]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import type { DataSource, Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            schemaCreate: false,
+            dropSchema: true,
+            enabledDrivers: ["mysql", "mssql"],
+            logging: true,
+        })
+    })
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("MySQL driver should include the call site stack trace on error", () =>
+        // [SPEC] When a query fails, the stack trace should include the function
+        // that initiated the query runner.
+
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function myNamedFunction123() {
+                    const queryRunner = dataSource.createQueryRunner()
+                    try {
+                        await queryRunner.query(
+                            "SELECT invalid_name FROM non_existent_table",
+                        )
+                    } finally {
+                        await queryRunner.release()
+                    }
+                }
+
+                // Confirm that the error contains the named function (in the stack trace).
+                await expect(myNamedFunction123())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("myNamedFunction123")
+            }),
+        ))
+
+    it("MySQL driver should include the call site stack trace on error when working with entities", () =>
+        // [SPEC] When working with entities and there is an error in a query, the stack
+        // trace should include the code that attempted the operation.
+
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function myNamedFunction1234() {
+                    const repository: Repository<Hygge> =
+                        dataSource.getRepository(Hygge)
+
+                    const hygge = repository.create()
+                    hygge.description =
+                        "Soft blankets and candlelight on a snowy evening."
+                    await repository.save(hygge)
+
+                    const hygge2 = repository.create()
+                    hygge2.id = hygge.id // Id collision.
+                    hygge2.description = "Eating homemade simply wonderfuls."
+                    await repository.insert(hygge2)
+                }
+
+                await expect(myNamedFunction1234())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("myNamedFunction1234")
+            }),
+        ))
+})
Evidence
PR Compliance ID 3 requires issue-fix tests to be added/updated in the functional suite, and
explicitly calls out adding tests only under test/github-issues as failure. This PR introduces new
issue-specific tests under test/github-issues/11271 (and its associated entity file) without any
clear justification for not placing them in test/functional.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11271/issue-11271.test.ts[1-76]
test/github-issues/11271/entity/hygge.ts[1-12]

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 issue-fix tests were added under `test/github-issues/11271`, but the compliance checklist requires issue fixes to live in the functional test suite (`test/functional`) unless there is a clear reason not to.
## Issue Context
These tests validate stack trace behavior for MySQL/MSSQL query runner errors; they should be represented as functional coverage rather than per-issue coverage.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-76]
- test/github-issues/11271/entity/hygge.ts[1-12]

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


3. Test added under test/github-issues 📘 Rule violation ≡ Correctness
Description
This PR adds a new issue regression test under test/github-issues/11271 rather than the functional
test suite. The compliance checklist requires issue fixes to live under test/functional unless
there is a clear reason.
Code

test/github-issues/11271/issue-11271.test.ts[R1-12]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import type { DataSource, Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
Evidence
PR Compliance ID 3 requires issue-fix tests to be added/updated in test/functional rather than
only under test/github-issues. The PR introduces a new test file under test/github-issues/11271,
indicating the issue fix is being tested only in the per-issue suite.

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

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

## Issue description
A new regression test for an issue fix was added under `test/github-issues`, but compliance requires issue-fix tests to live in the functional test suite (`test/functional`) unless there is a clear justification.
## Issue Context
The checklist item &quot;Prefer functional tests over per-issue tests&quot; expects tests for issue fixes to be placed under `test/functional`.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-76]

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


View more (3)
4. Issue test in github-issues 📘 Rule violation ≡ Correctness
Description
New coverage for an issue fix is added under test/github-issues/11271 without a clear reason it
cannot live in the functional test suite. This conflicts with the requirement to prefer functional
tests for issue fixes.
Code

test/github-issues/11271/issue-11271.test.ts[R1-23]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { DataSource } from "../../../src/data-source/DataSource"
+import { Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            schemaCreate: false,
+            dropSchema: true,
+            enabledDrivers: ["mysql", "mssql"],
+            logging: true,
+        })
+    })
Evidence
The compliance checklist requires issue-fix tests to be added/updated in test/functional rather
than test/github-issues unless there is a clear reason; the PR adds a new issue test under
test/github-issues/11271 and does not document an exception in-code.

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

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

## Issue description
Tests for an issue fix were added under `test/github-issues` instead of the functional test suite, without a clear exception.
## Issue Context
Compliance requires issue-fix coverage to live in `test/functional` when possible, with an issue reference comment if applicable.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-77]
- test/github-issues/11271/entity/hygge.ts[1-12]

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


5. promisifyMethod double-rejects 🐞 Bug ≡ Correctness
Description
ObjectUtils.promisifyMethod rejects when the method is missing but then still attempts to call it,
which can trigger a synchronous exception and a second reject. This can produce confusing/noisy
failures and makes diagnosing the original error harder.
Code

src/util/ObjectUtils.ts[R92-110]

+            const fn = obj?.[method]
+            if (typeof fn !== "function") {
+                reject(new Error(`Object does not have method ${method}`))
+            }
+
+            try {
+                fn.call(
+                    obj,
+                    ...args,
+                    (err: Error | null | undefined, result?: T) => {
+                        if (err) {
+                            reject(err)
+                        } else {
+                            resolve(result as T)
+                        }
+                    },
+                )
+            } catch (err) {
+                reject(err)
Evidence
The implementation calls reject(...) for a missing method but does not return, so execution
continues into fn.call(...) even when fn is not a function (leading to an exception path and a
second reject).

src/util/ObjectUtils.ts[84-114]

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

## Issue description
`ObjectUtils.promisifyMethod` calls `reject(...)` when the requested method is missing, but continues executing and attempts `fn.call(...)` anyway. This can throw and cause a second rejection, making errors noisy/confusing.
### Issue Context
This helper is now used by MySQL and SQL Server query runners; while the “method missing” case should be rare, when it happens it will be harder to debug due to double-failure behavior.
### Fix Focus Areas
- src/util/ObjectUtils.ts[91-111]

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


6. Pool error skips AfterQuery 🐞 Bug ≡ Correctness
Description
SqlServerQueryRunner.query() acquires the pool after emitting BeforeQuery, but pool acquisition is
outside the inner try/catch that logs errors and broadcasts AfterQuery. If
obtainMaster/SlaveConnection rejects, the method exits via finally without broadcasting AfterQuery
or logging/wrapping the error with query context, leaving subscribers in an inconsistent state
(BeforeQuery without AfterQuery).
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R223-227]

try {
const pool = await (this.mode === "slave"
 ? this.driver.obtainSlaveConnection()
 : this.driver.obtainMasterConnection())
-            const request = new this.driver.mssql.Request(
-                this.isTransactionActive ? this.databaseConnection : pool,
-            )
-            if (parameters && parameters.length) {
-                parameters.forEach((parameter, index) => {
-                    const parameterName = index.toString()
-                    if (InstanceChecker.isMssqlParameter(parameter)) {
-                        const mssqlParameter =
-                            this.mssqlParameterToNativeParameter(parameter)
-                        if (mssqlParameter) {
-                            request.input(
-                                parameterName,
-                                mssqlParameter,
-                                parameter.value,
-                            )
+
Evidence
SqlServerQueryRunner broadcasts BeforeQuery, then awaits
obtainSlaveConnection/obtainMasterConnection, and only the subsequent inner block is protected by a
catch that logs/broadcasts AfterQuery. Because the pool await happens before the inner `try { ...
} catch { ... }`, a rejection from obtainMasterConnection bypasses the only catch that calls
logQueryError/broadcastAfterQueryEvent. SqlServerDriver.obtainMasterConnection can indeed reject
(e.g., when the driver is not connected). Missing broadcastAfterQueryEvent means
subscriber.afterQuery hooks won’t run.

src/driver/sqlserver/SqlServerQueryRunner.ts[214-351]
src/driver/sqlserver/SqlServerDriver.ts[782-788]
src/subscriber/Broadcaster.ts[471-510]

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

## Issue description
`SqlServerQueryRunner.query()` emits `BeforeQuery` and then awaits `obtainMasterConnection/obtainSlaveConnection()` outside the only `catch` that logs and broadcasts `AfterQuery`. If pool acquisition rejects, the function exits via `finally` without `broadcastAfterQueryEvent(false, ...)`, so subscribers may see `BeforeQuery` without a matching `AfterQuery`, and the error is not logged/wrapped with query context.
### Issue Context
- `SqlServerDriver.obtainMasterConnection()` can reject with `TypeORMError(&amp;amp;amp;amp;quot;Driver not Connected&amp;amp;amp;amp;quot;)`.
- `broadcastAfterQueryEvent` is what triggers `subscriber.afterQuery`.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[214-351]
- src/driver/sqlserver/SqlServerDriver.ts[782-788]
- src/subscriber/Broadcaster.ts[471-510]
### Suggested change
Refactor `query()` to use a single `try/catch/finally` (or add an outer `catch`) that covers pool acquisition as well as request/query execution, and in that catch:
- call `this.driver.connection.logger.logQueryError(err, query, parameters, this)`
- call `this.broadcaster.broadcastAfterQueryEvent(broadcasterResult, query, parameters, false, /*executionTime*/ undefined, undefined, err)`
- throw a `QueryFailedError(query, parameters, err)` (or preserve existing `QueryFailedError` instances)

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



Remediation recommended

7. No docs for stack change 📘 Rule violation ⚙ Maintainability ⭐ New
Description
This PR changes query error behavior to preserve/include call-site stack traces (validated by new
functional tests), which is user-observable. No documentation updates are included in the PR to
describe this behavior change.
Code

test/functional/query-runner/error-stack-trace.test.ts[R23-40]

+    it("should include call site stack trace on query error", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function myNamedFunction123() {
+                    const queryRunner = dataSource.createQueryRunner()
+                    try {
+                        await queryRunner.query(
+                            "SELECT invalid_name FROM non_existent_table",
+                        )
+                    } finally {
+                        await queryRunner.release()
+                    }
+                }
+
+                await expect(myNamedFunction123())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("myNamedFunction123")
+            }),
Evidence
PR Compliance ID 2 requires docs to be updated for user-facing behavior changes. The new tests
explicitly assert that the thrown error stack includes the caller function name, and the query
runners now throw QueryFailedError from the async/await path; however, the provided PR diff
contains no docs changes.

Rule 2: Docs updated for user-facing changes
test/functional/query-runner/error-stack-trace.test.ts[23-40]
src/driver/mysql/MysqlQueryRunner.ts[262-294]

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 PR introduces a user-observable change: query errors should include the call-site stack trace (as asserted by new functional tests), but documentation was not updated to reflect this.

## Issue Context
The change affects how `QueryRunner.query()` and related operations surface error stack traces to application developers.

## Fix Focus Areas
- docs/docs/query-runner.md[1-96]

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


8. Hot-path promisify allocations 🐞 Bug ➹ Performance
Description
MysqlQueryRunner.query and SqlServerQueryRunner.query allocate new promisified+bound wrapper
functions on every query execution, adding avoidable allocations/GC pressure on the hottest code
path (query execution). This can regress throughput in workloads that execute many small queries.
Code

src/driver/mysql/MysqlQueryRunner.ts[R220-224]

+        try {
+            const dbcQuery = promisify(databaseConnection.query).bind(
+                databaseConnection,
+            )
+            const raw = await dbcQuery(queryPayload, parameters)
Evidence
Both query runners create a new wrapper function inside query() for every invocation:
promisify(fn) allocates a new function and .bind(...) allocates another, and this is done per
query call rather than once per connection/request lifecycle.

src/driver/mysql/MysqlQueryRunner.ts[211-225]
src/driver/sqlserver/SqlServerQueryRunner.ts[232-269]

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

## Issue description
`query()` currently creates `promisify(...).bind(...)` wrappers on every call, causing avoidable allocations on a hot path.
### Issue Context
This happens in both MySQL and SQL Server query runners after replacing the manual Promise wrapper.
### Fix Focus Areas
- src/driver/mysql/MysqlQueryRunner.ts[211-225]
- src/driver/sqlserver/SqlServerQueryRunner.ts[263-268]
### Suggested approach
- **MySQL:** cache the promisified function per underlying `databaseConnection` (e.g., via a `WeakMap<Connection, Function>` or attaching a non-enumerable symbol property to the connection), so repeated queries reuse the same wrapper.
- **SQL Server:** avoid `.bind()` allocation by using `promisify(request.query).call(request, query)` (still allocates the promisified wrapper), or (if supported by the driver in this codebase) use the native promise API directly to avoid `promisify` entirely.

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


9. Bogus slow-query timing 🐞 Bug ✧ Quality
Description
SqlServerQueryRunner computes queryExecutionTime in the catch block using `Date.now() -
queryStartTime even when queryStartTime` was never set (it defaults to 0). If an error happens
before queryStartTime = Date.now() (e.g., during pool acquisition or parameter binding), this can
log a huge/incorrect slow-query duration and create noisy/misleading diagnostics.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R309-320]

+            const queryExecutionTime = Date.now() - queryStartTime
+
+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime > maxQueryExecutionTime
+            )
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
Evidence
queryStartTime is initialized to 0 and only assigned immediately before executing the request
query. However, the catch block always computes a duration and may log it as a slow query, even for
failures that occur before the assignment. MySQL’s runner sets queryStartTime before entering the
try/catch, avoiding this specific hazard.

src/driver/sqlserver/SqlServerQueryRunner.ts[219-257]
src/driver/sqlserver/SqlServerQueryRunner.ts[308-320]
src/driver/mysql/MysqlQueryRunner.ts[201-216]

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

## Issue description
`SqlServerQueryRunner.query()` initializes `queryStartTime` to `0` and uses it in the catch block slow-query logger. If the failure occurs before `queryStartTime = Date.now()` (e.g., while obtaining a pool connection or binding inputs), the computed duration becomes `Date.now() - 0`, producing a huge value and misleading `logQuerySlow()` output.
### Issue Context
This PR added slow-query logging in the SQL Server error path. The MySQL runner avoids this specific pitfall by setting `queryStartTime` before entering the try/catch.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[219-340]
### Suggested changes
- Update the catch block to only compute/log slow-query time if `queryStartTime &gt; 0`.
- Example:
- `if (queryStartTime &gt; 0) { const queryExecutionTime = Date.now() - queryStartTime; ... }`
- Alternatively, set `queryStartTime = Date.now()` at a point that is guaranteed to execute before any operation that could throw, but still consider whether you want connection acquisition / parameter binding time included in “query execution time.”

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


View more (4)
10. my_named_function_123 non-camelCase 📘 Rule violation ≡ Correctness
Description
The newly added test defines functions named my_named_function_123 and my_named_function_1234,
which do not follow typical project camelCase naming for functions. This reduces consistency and
readability of new code.
Code

test/github-issues/11271/issue-11271.test.ts[R33-58]

+                async function my_named_function_123() {
+                    const queryRunner = dataSource.createQueryRunner()
+                    try {
+                        await queryRunner.query(
+                            "SELECT invalid_name FROM non_existent_table",
+                        )
+                    } finally {
+                        await queryRunner.release()
+                    }
+                }
+
+                // Confirm that the error contains the named function (in the stack trace).
+                await expect(my_named_function_123())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("my_named_function_123")
+            }),
+        ))
+
+    it("MySQL driver should include the call site stack trace on error when working with entities", () =>
+        // [SPEC] When working with entities and there is an error in a query, the stack
+        // trace should include the code that attempted the operation.
+
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function my_named_function_1234() {
+                    const repository: Repository<Hygge> =
Evidence
Compliance requires new identifiers to follow established naming conventions; the added function
identifiers use snake_case with numbers instead of the expected convention.

Rule 1: Consistent Naming Conventions
test/github-issues/11271/issue-11271.test.ts[33-34]
test/github-issues/11271/issue-11271.test.ts[57-60]

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

## Issue description
Newly introduced function names in tests (e.g., `my_named_function_123`) do not follow the project&amp;#x27;s naming conventions.
## Issue Context
The compliance checklist requires consistent naming for all new identifiers.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[33-74]

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


11. promisifyMethod uses any-casts 📘 Rule violation ≡ Correctness
Description
The new ObjectUtils.promisifyMethod introduces broad any typing (obj: any, ...args: any[])
and a cast (result as T) that can mask type errors. This may be considered type-bypassing noise
per the checklist and can reduce type safety.
Code

src/util/ObjectUtils.ts[R86-100]

+    static promisifyMethod<T = any>(
+        obj: any,
+        method: string,
+        ...args: any[]
+    ): Promise<T> {
+        return new Promise<T>((resolve, reject) => {
+            obj[method](
+                ...args,
+                (err: Error | null | undefined, result?: T) => {
+                    if (err) {
+                        reject(err)
+                    } else {
+                        resolve(result as T)
+                    }
+                },
Evidence
The checklist disallows introducing any-casts to bypass type issues; the added helper relies on
any parameters and an explicit cast when resolving the promise.

Rule 4: Remove AI-generated noise
src/util/ObjectUtils.ts[86-90]
src/util/ObjectUtils.ts[94-100]

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

## Issue description
`ObjectUtils.promisifyMethod` introduces broad `any` usage and an explicit cast (`result as T`), which can bypass TypeScript&amp;#x27;s type checking.
## Issue Context
The compliance checklist flags `any`-casts/type bypasses and style that looks like defensive/AI-generated noise.
## Fix Focus Areas
- src/util/ObjectUtils.ts[86-103]

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


12. Missing slow-log on error 🐞 Bug ≡ Correctness
Description
SqlServerQueryRunner now only calls logQuerySlow after a successful query; slow queries that fail
(timeouts, deadlocks) won’t be logged as slow, reducing observability for performance incidents.
This is inconsistent with MysqlQueryRunner, which logs slow queries in both success and error paths.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R271-281]

+            if (
+                maxQueryExecutionTime &&
+                queryExecutionTime > maxQueryExecutionTime
+            ) {
+                this.driver.connection.logger.logQuerySlow(
+                    queryExecutionTime,
+                    query,
+                    parameters,
+                    this,
+                )
+            }
Evidence
In SqlServerQueryRunner, slow-query logging is executed only after the awaited query completes
successfully, and the catch path does not compute execution time or log slow queries.
MysqlQueryRunner explicitly logs slow queries in its catch path, indicating the codebase expects
slow-query visibility even when the query fails.

src/driver/sqlserver/SqlServerQueryRunner.ts[248-281]
src/driver/sqlserver/SqlServerQueryRunner.ts[308-326]
src/driver/mysql/MysqlQueryRunner.ts[256-268]

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

## Issue description
`SqlServerQueryRunner.query()` only calls `logQuerySlow` on the success path. Slow queries that ultimately error (timeouts, deadlocks, etc.) won’t emit slow-query logs, reducing observability.
## Issue Context
`MysqlQueryRunner.query()` logs slow queries in both success and catch paths. SQL Server should do the same for consistency and to retain slow-query visibility when failures occur.
## Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[308-326]
- src/driver/sqlserver/SqlServerQueryRunner.ts[248-281]

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


13. SqlServer wraps connect errors 🐞 Bug ≡ Correctness
Description
SqlServerQueryRunner.query() now wraps *all* errors into QueryFailedError, including
connection-acquisition failures like TypeORMError("Driver not Connected"). This changes the public
error type/semantics for connection-level failures compared to other drivers (which obtain
connections outside the QueryFailedError-wrapping try/catch).
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[341]

+            throw new QueryFailedError(query, parameters, err)
Evidence
obtainMasterConnection() can reject with a TypeORMError("Driver not Connected"). Because SQL
Server’s query() awaits obtain*Connection() inside the same try/catch that unconditionally
throws new QueryFailedError(...), this connection-level error gets reclassified as a query
failure. In contrast, MySQL and Postgres acquire databaseConnection via connect() before the
wrapping try/catch, so connect/acquire errors typically propagate without being converted to
QueryFailedError.

src/driver/sqlserver/SqlServerDriver.ts[778-788]
src/driver/sqlserver/SqlServerQueryRunner.ts[219-342]
src/driver/mysql/MysqlQueryRunner.ts[189-216]
src/driver/postgres/PostgresQueryRunner.ts[244-262]

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

## Issue description
`SqlServerQueryRunner.query()` unconditionally wraps any caught error in `QueryFailedError`, which reclassifies non-query failures like `TypeORMError(&quot;Driver not Connected&quot;)` (from `obtainMasterConnection`) into query failures.
### Issue Context
Other query runners typically obtain the connection before the try/catch that wraps into `QueryFailedError`, so connection-level failures are not converted. Preserving this distinction helps callers differentiate between connectivity/driver state issues vs. SQL execution problems.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[219-226]
- src/driver/sqlserver/SqlServerQueryRunner.ts[308-342]

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


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Previous review results

Review updated until commit 65a51fb

Results up to commit 673a4e9


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


Action required
1. Issue tests added under test/github-issues 📘 Rule violation ⚙ Maintainability
Description
New tests for this issue were added under test/github-issues/11271 instead of the functional test
suite. This violates the requirement to keep issue fixes in test/functional unless there is a
clear documented reason.
Code

test/github-issues/11271/issue-11271.test.ts[R1-76]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import type { DataSource, Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            schemaCreate: false,
+            dropSchema: true,
+            enabledDrivers: ["mysql", "mssql"],
+            logging: true,
+        })
+    })
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("MySQL driver should include the call site stack trace on error", () =>
+        // [SPEC] When a query fails, the stack trace should include the function
+        // that initiated the query runner.
+
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function myNamedFunction123() {
+                    const queryRunner = dataSource.createQueryRunner()
+                    try {
+                        await queryRunner.query(
+                            "SELECT invalid_name FROM non_existent_table",
+                        )
+                    } finally {
+                        await queryRunner.release()
+                    }
+                }
+
+                // Confirm that the error contains the named function (in the stack trace).
+                await expect(myNamedFunction123())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("myNamedFunction123")
+            }),
+        ))
+
+    it("MySQL driver should include the call site stack trace on error when working with entities", () =>
+        // [SPEC] When working with entities and there is an error in a query, the stack
+        // trace should include the code that attempted the operation.
+
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                async function myNamedFunction1234() {
+                    const repository: Repository<Hygge> =
+                        dataSource.getRepository(Hygge)
+
+                    const hygge = repository.create()
+                    hygge.description =
+                        "Soft blankets and candlelight on a snowy evening."
+                    await repository.save(hygge)
+
+                    const hygge2 = repository.create()
+                    hygge2.id = hygge.id // Id collision.
+                    hygge2.description = "Eating homemade simply wonderfuls."
+                    await repository.insert(hygge2)
+                }
+
+                await expect(myNamedFunction1234())
+                    .to.be.rejected.and.eventually.have.property("stack")
+                    .that.include("myNamedFunction1234")
+            }),
+        ))
+})
Evidence
PR Compliance ID 3 requires issue-fix tests to be added/updated in the functional suite, and
explicitly calls out adding tests only under test/github-issues as failure. This PR introduces new
issue-specific tests under test/github-issues/11271 (and its associated entity file) without any
clear justification for not placing them in test/functional.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11271/issue-11271.test.ts[1-76]
test/github-issues/11271/entity/hygge.ts[1-12]

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 issue-fix tests were added under `test/github-issues/11271`, but the compliance checklist requires issue fixes to live in the functional test suite (`test/functional`) unless there is a clear reason not to.
## Issue Context
These tests validate stack trace behavior for MySQL/MSSQL query runner errors; they should be represented as functional coverage rather than per-issue coverage.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-76]
- test/github-issues/11271/entity/hygge.ts[1-12]

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


2. Test added under test/github-issues 📘 Rule violation ≡ Correctness
Description
This PR adds a new issue regression test under test/github-issues/11271 rather than the functional
test suite. The compliance checklist requires issue fixes to live under test/functional unless
there is a clear reason.
Code

test/github-issues/11271/issue-11271.test.ts[R1-12]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import type { DataSource, Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
Evidence
PR Compliance ID 3 requires issue-fix tests to be added/updated in test/functional rather than
only under test/github-issues. The PR introduces a new test file under test/github-issues/11271,
indicating the issue fix is being tested only in the per-issue suite.

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

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

## Issue description
A new regression test for an issue fix was added under `test/github-issues`, but compliance requires issue-fix tests to live in the functional test suite (`test/functional`) unless there is a clear justification.
## Issue Context
The checklist item &quot;Prefer functional tests over per-issue tests&quot; expects tests for issue fixes to be placed under `test/functional`.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-76]

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


3. Issue test in github-issues 📘 Rule violation ≡ Correctness
Description
New coverage for an issue fix is added under test/github-issues/11271 without a clear reason it
cannot live in the functional test suite. This conflicts with the requirement to prefer functional
tests for issue fixes.
Code

test/github-issues/11271/issue-11271.test.ts[R1-23]

+import "reflect-metadata"
+import {
+    createTestingConnections,
+    closeTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { DataSource } from "../../../src/data-source/DataSource"
+import { Repository } from "../../../src"
+import { expect } from "chai"
+import { Hygge } from "./entity/hygge"
+
+describe("github issues > #11271 Stack trace is truncated in MySQL query runner", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [__dirname + "/entity/*{.js,.ts}"],
+            schemaCreate: false,
+            dropSchema: true,
+            enabledDrivers: ["mysql", "mssql"],
+            logging: true,
+        })
+    })
Evidence
The compliance checklist requires issue-fix tests to be added/updated in test/functional rather
than test/github-issues unless there is a clear reason; the PR adds a new issue test under
test/github-issues/11271 and does not document an exception in-code.

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

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

## Issue description
Tests for an issue fix were added under `test/github-issues` instead of the functional test suite, without a clear exception.
## Issue Context
Compliance requires issue-fix coverage to live in `test/functional` when possible, with an issue reference comment if applicable.
## Fix Focus Areas
- test/github-issues/11271/issue-11271.test.ts[1-77]
- test/github-issues/11271/entity/hygge.ts[1-12]

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


View more (2)
4. promisifyMethod double-rejects 🐞 Bug ≡ Correctness
Description
ObjectUtils.promisifyMethod rejects when the method is missing but then still attempts to call it,
which can trigger a synchronous exception and a second reject. This can produce confusing/noisy
failures and makes diagnosing the original error harder.
Code

src/util/ObjectUtils.ts[R92-110]

+            const fn = obj?.[method]
+            if (typeof fn !== "function") {
+                reject(new Error(`Object does not have method ${method}`))
+            }
+
+            try {
+                fn.call(
+                    obj,
+                    ...args,
+                    (err: Error | null | undefined, result?: T) => {
+                        if (err) {
+                            reject(err)
+                        } else {
+                            resolve(result as T)
+                        }
+                    },
+                )
+            } catch (err) {
+                reject(err)
Evidence
The implementation calls reject(...) for a missing method but does not return, so execution
continues into fn.call(...) even when fn is not a function (leading to an exception path and a
second reject).

src/util/ObjectUtils.ts[84-114]

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

## Issue description
`ObjectUtils.promisifyMethod` calls `reject(...)` when the requested method is missing, but continues executing and attempts `fn.call(...)` anyway. This can throw and cause a second rejection, making errors noisy/confusing.
### Issue Context
This helper is now used by MySQL and SQL Server query runners; while the “method missing” case should be rare, when it happens it will be harder to debug due to double-failure behavior.
### Fix Focus Areas
- src/util/ObjectUtils.ts[91-111]

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


5. Pool error skips AfterQuery 🐞 Bug ≡ Correctness
Description
SqlServerQueryRunner.query() acquires the pool after emitting BeforeQuery, but pool acquisition is
outside the inner try/catch that logs errors and broadcasts AfterQuery. If
obtainMaster/SlaveConnection rejects, the method exits via finally without broadcasting AfterQuery
or logging/wrapping the error with query context, leaving subscribers in an inconsistent state
(BeforeQuery without AfterQuery).
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R223-227]

try {
const pool = await (this.mode === "slave"
  ? this.driver.obtainSlaveConnection()
  : this.driver.obtainMasterConnection())
-            const request = new this.driver.mssql.Request(
-                this.isTransactionActive ? this.databaseConnection : pool,
-            )
-            if (parameters && parameters.length) {
-                parameters.forEach((parameter, index) => {
-                    const parameterName = index.toString()
-                    if (InstanceChecker.isMssqlParameter(parameter)) {
-                        const mssqlParameter =
-                            this.mssqlParameterToNativeParameter(parameter)
-                        if (mssqlParameter) {
-                            request.input(
-                                parameterName,
-                                mssqlParameter,
-                                parameter.value,
-                            )
+
Evidence
SqlServerQueryRunner broadcasts BeforeQuery, then awaits
obtainSlaveConnection/obtainMasterConnection, and only the subsequent inner block is protected by a
catch that logs/broadcasts AfterQuery. Because the pool await happens before the inner `try { ...
} catch { ... }`, a rejection from obtainMasterConnection bypasses the only catch that calls
logQueryError/broadcastAfterQueryEvent. SqlServerDriver.obtainMasterConnection can indeed reject
(e.g., when the driver is not connected). Missing broadcastAfterQueryEvent means
subscriber.afterQuery hooks won’t run.

src/driver/sqlserver/SqlServerQueryRunner.ts[214-351]
src/driver/sqlserver/SqlServerDriver.ts[782-788]
src/subscriber/Broadcaster.ts[471-510]

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

## Issue description
`SqlServerQueryRunner.query()` emits `BeforeQuery` and then awaits `obtainMasterConnection/obtainSlaveConnection()` outside the only `catch` that logs and broadcasts `AfterQuery`. If pool acquisition rejects, the function exits via `finally` without `broadcastAfterQueryEvent(false, ...)`, so subscribers may see `BeforeQuery` without a matching `AfterQuery`, and the error is not logged/wrapped with query context.
### Issue Context
- `SqlServerDriver.obtainMasterConnection()` can reject with `TypeO...

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch 2 times, most recently from ce09f9e to 509df80 Compare February 28, 2026 09:49
@coveralls

coveralls commented Feb 28, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 73.704% (-0.04%) from 73.745% — Cprakhar:fix-mysql-stack-trace into typeorm:master

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch 5 times, most recently from 60c71cc to 0690d1b Compare March 6, 2026 11:53
@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch from 0690d1b to 47dbd26 Compare March 9, 2026 14:58
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 47dbd26

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch from 47dbd26 to 660e0bd Compare March 29, 2026 13:24
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 660e0bd

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch from 660e0bd to 0799d9f Compare April 2, 2026 15:30
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 0799d9f

@sonarqubecloud

Copy link
Copy Markdown

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8d80e0d

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8d2f8d9

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

Copy link
Copy Markdown

Persistent review updated to latest commit efe437e

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch from efe437e to 673a4e9 Compare April 24, 2026 10:19
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 673a4e9

@Cprakhar
Cprakhar force-pushed the fix-mysql-stack-trace branch from 673a4e9 to 65a51fb Compare April 24, 2026 11:07
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 65a51fb

@Cprakhar
Cprakhar requested a review from alumni April 24, 2026 11:53
@alumni

alumni commented Apr 24, 2026

Copy link
Copy Markdown
Collaborator

nice 🥳 happy to see the usage of promise go away. will take a better look once I have some time :)

@alumni
alumni merged commit 24677a1 into typeorm:master Apr 24, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone Apr 24, 2026
@Cprakhar
Cprakhar deleted the fix-mysql-stack-trace branch June 13, 2026 21:43
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.

how to print real location in code, when the typeorm throw error Stack trace is truncated in SQL Server query runner

5 participants