You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
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.
✅ Handle early failures consistentlySuggestion 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.
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.
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.
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.
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.
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.
In the catch block of the query method, pass the calculated queryExecutionTime to broadcastAfterQueryEvent instead of undefined to provide consistent timing data on errors.
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 methodsSuggestion 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.
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
Category
Suggestion
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.
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 loggingSuggestion 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.
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.
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.
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.
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.
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.
+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.
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.
+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.
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 "Prefer functional tests over per-issue tests" 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.
+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.
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
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.
+ 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).
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).
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.
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;quot;Driver not Connected&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
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.
+ 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.
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
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.
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.
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.
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.
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 > 0`.
- Example:
- `if (queryStartTime > 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.
+ 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.
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&#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
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.
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.
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&#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.
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.
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
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).
+ 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.
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("Driver not Connected")` (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
Author self-review: I have reviewed the code review findings, and addressed the relevant ones.
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.
+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.
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.
+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.
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 "Prefer functional tests over per-issue tests" 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.
+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.
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.
+ 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).
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).
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.
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...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of change
This PR continues the work from #11273
Closes #11499
Closes #11765
Changes
mysql2package supports promise via.promise()methodqueryin mssqlPull-Request Checklist
masterbranchFixes #11765 #11499tests/**.test.ts)docs/docs/**.md) (N/A)