Skip to content

fix(driver): broadcast query events in capacitor and nativescript drivers - #12724

Open
kyungseopk1m wants to merge 3 commits into
typeorm:masterfrom
kyungseopk1m:fix/capacitor-nativescript-query-broadcast
Open

kyungseopk1m wants to merge 3 commits into
typeorm:masterfrom
kyungseopk1m:fix/capacitor-nativescript-query-broadcast

Conversation

@kyungseopk1m

Copy link
Copy Markdown
Contributor

Description

The Capacitor and NativeScript query runners never emit the beforeQuery / afterQuery subscriber events. Subscribers registered through these two drivers are therefore never invoked, unlike every other SQLite-family driver (better-sqlite3, cordova, expo, sqljs, react-native), all of which broadcast these events from their query() method.

This has been the case since both drivers were added; they never contained the broadcast calls.

Fix

Add the beforeQuery / afterQuery broadcasts to each driver's query(), mirroring the existing sibling drivers.

  • Capacitor already awaits the DB call inside an async method, so the added broadcasts follow the same shape as the other async runners.
  • NativeScript wraps a callback-based native call, so the DB result is only available inside the callback. The afterQuery broadcast and await broadcasterResult.wait() are therefore placed inside the callback, right before resolving or rejecting, so that async subscribers settle before the query promise does. This is done on both the success and failure paths. The failure branch also gains a return that was missing: without it the handler fell through after fail() and produced a second, spurious success result (previously harmless only because resolving an already-rejected promise is a no-op, but it would now emit an incorrect success event).

Tests

Added test/unit/driver/query-broadcast-events.test.ts covering Capacitor and NativeScript, success and failure, each asserting that an async afterQuery subscriber has fully settled before query() resolves/rejects. With the previous (broken) NativeScript ordering the success/failure cases resolve before the subscriber settles; with the fix all four pass. The rest of the unit suite passes unchanged.

These two drivers target mobile runtimes that are not exercised in CI, so verification is at the unit level against the broadcaster contract.

@github-actions github-actions Bot added the needs-triage PR needs issue link triage label Jul 21, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 21, 2026 •

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

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

commit: f5c451a

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

qodo-free-for-open-source-projects Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Async callback can hang ✓ Resolved 🐞 Bug ☼ Reliability
Description
In NativescriptQueryRunner.query(), the native callback handler is now async and awaits
broadcasterResult.wait(); if any afterQuery subscriber promise rejects, the handler throws/rejects
but nothing catches it, so ok()/fail() is never called and the query() Promise can remain pending
indefinitely.
Code

src/driver/nativescript/NativescriptQueryRunner.ts[R101-112]

+                    this.broadcaster.broadcastAfterQueryEvent(
+                        broadcasterResult,
+                        query,
+                        parameters,
+                        false,
+                        undefined,
+                        undefined,
+                        err,
+                    )
+                    await broadcasterResult.wait()
                fail(new QueryFailedError(query, parameters, err))
+                    return
Evidence
The handler awaits BroadcasterResult.wait() before calling ok()/fail(), but since it is used as a
callback the returned promise is ignored; if wait() rejects, control exits before ok()/fail() and
the outer promise is left pending. BroadcasterResult.wait() uses Promise.all, so a rejecting
subscriber promise will reject wait().

src/driver/nativescript/NativescriptQueryRunner.ts[72-146]
src/subscriber/Broadcaster.ts[499-528]
src/subscriber/BroadcasterResult.ts[15-24]

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

## Issue description
`NativescriptQueryRunner.query()` passes an `async` handler to callback-style native APIs (`databaseConnection.all/execSQL`). Any rejection thrown by `await broadcasterResult.wait()` is not caught/forwarded to `fail()`, so the outer `Promise` can remain pending forever.
## Issue Context
`BroadcasterResult.wait()` awaits `Promise.all(...)`, which rejects if any subscriber promise rejects. Because the native API ignores the handler’s returned promise, those rejections won’t naturally propagate to the outer promise.
## Fix Focus Areas
- src/driver/nativescript/NativescriptQueryRunner.ts[72-146]
## Suggested fix
Wrap the handler body (including `await broadcasterResult.wait()`) in a try/catch that always settles the outer promise, e.g.:
- Keep `handler` non-async and drive settling via `.then/.catch`, OR
- Use an async IIFE and explicitly catch:

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



Remediation recommended

2. Sync subscriber masks error ⊘ Outdated 🐞 Bug ☼ Reliability
Description
In CapacitorQueryRunner.query()’s catch block, broadcastAfterQueryEvent() is invoked outside the
try/catch that only guards broadcasterResult.wait(), so a synchronous throw from an afterQuery
subscriber can escape and replace the original database error. This defeats the intended behavior of
preserving the original query failure when broadcasting afterQuery on errors.
Code

src/driver/capacitor/CapacitorQueryRunner.ts[R106-114]

+            this.broadcaster.broadcastAfterQueryEvent(
+                broadcasterResult,
+                query,
+                parameters,
+                false,
+                undefined,
+                undefined,
+                err,
+            )
Evidence
Capacitor’s catch block only protects broadcasterResult.wait(); since broadcastAfterQueryEvent()
invokes subscriber.afterQuery() without a try/catch, a synchronous subscriber throw will propagate
and prevent throwing QueryFailedError for the original query failure.

src/driver/capacitor/CapacitorQueryRunner.ts[99-122]
src/subscriber/Broadcaster.ts[499-528]

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

## Issue description
In `CapacitorQueryRunner.query()`’s error path, `broadcastAfterQueryEvent(...)` can throw synchronously (e.g., a subscriber throws before returning), which bypasses the intended `QueryFailedError` and masks the original query error.
## Issue Context
`Broadcaster.broadcastAfterQueryEvent` calls `subscriber.afterQuery(...)` directly and does not wrap subscriber execution in a try/catch, so synchronous throws propagate to the caller.
## Fix Focus Areas
- src/driver/capacitor/CapacitorQueryRunner.ts[99-121]
- src/subscriber/Broadcaster.ts[499-528]
## Suggested fix
Wrap both the `broadcastAfterQueryEvent(...)` call *and* the subsequent `await broadcasterResult.wait()` in a single try/catch in the query failure path, swallowing subscriber errors so the original query error is always rethrown as `QueryFailedError`.
Example shape:

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


3. any types in test ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new unit test disables no-explicit-any and uses any for driver/dataSource stubs, which
weakens type-safety and can hide real contract mismatches. This conflicts with the guideline to
avoid any usage added to bypass type issues.
Code

test/unit/driver/query-broadcast-events.test.ts[R1-18]

+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { expect } from "chai"
+import { CapacitorQueryRunner } from "../../../src/driver/capacitor/CapacitorQueryRunner"
+import { NativescriptQueryRunner } from "../../../src/driver/nativescript/NativescriptQueryRunner"
+
+function delay(ms: number): Promise<void> {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/**
+ * A minimal DataSource stub with a single subscriber whose afterQuery hook
+ * does real async work, so tests can tell whether query() waited for it.
+ */
+function makeDataSource() {
+    let subscriberSettled = false
+    const dataSource: any = {
+        logger: { logQuery() {}, logQueryError() {}, logQuerySlow() {} },
+        manager: {},
Evidence
PR Compliance ID 4 forbids introducing any casts/usage to bypass type issues. The added test file
explicitly disables the no-explicit-any rule and defines dataSource/driver as any, meeting
the failure criteria.

Rule 4: Remove AI-generated noise
test/unit/driver/query-broadcast-events.test.ts[1-27]

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 unit test introduces `/* eslint-disable @typescript-eslint/no-explicit-any */` and multiple `any`-typed stubs, which reduces maintainability and may mask type regressions.
## Issue Context
The compliance checklist asks to avoid AI-generated noise patterns such as `any` usage to bypass types. Even in tests, minimal typing (or `unknown` + narrowing) improves correctness and future refactors.
## Fix Focus Areas
- test/unit/driver/query-broadcast-events.test.ts[1-31]

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

Grey Divider

Context sources
Review mode: ⚖️ Balanced: This changes runtime query execution and subscriber/error-settlement behavior across two drivers, carrying meaningful asynchronous control-flow and error-propagation risk, but not enough independent complexity to warrant extended review.

Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit f5c451a ⚖️ Balanced

Results up to commit 536ea9b


🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)


Action required
1. Async callback can hang ✓ Resolved 🐞 Bug ☼ Reliability
Description
In NativescriptQueryRunner.query(), the native callback handler is now async and awaits
broadcasterResult.wait(); if any afterQuery subscriber promise rejects, the handler throws/rejects
but nothing catches it, so ok()/fail() is never called and the query() Promise can remain pending
indefinitely.
Code

src/driver/nativescript/NativescriptQueryRunner.ts[R101-112]

+                    this.broadcaster.broadcastAfterQueryEvent(
+                        broadcasterResult,
+                        query,
+                        parameters,
+                        false,
+                        undefined,
+                        undefined,
+                        err,
+                    )
+                    await broadcasterResult.wait()
                  fail(new QueryFailedError(query, parameters, err))
+                    return
Evidence
The handler awaits BroadcasterResult.wait() before calling ok()/fail(), but since it is used as a
callback the returned promise is ignored; if wait() rejects, control exits before ok()/fail() and
the outer promise is left pending. BroadcasterResult.wait() uses Promise.all, so a rejecting
subscriber promise will reject wait().

src/driver/nativescript/NativescriptQueryRunner.ts[72-146]
src/subscriber/Broadcaster.ts[499-528]
src/subscriber/BroadcasterResult.ts[15-24]

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

## Issue description
`NativescriptQueryRunner.query()` passes an `async` handler to callback-style native APIs (`databaseConnection.all/execSQL`). Any rejection thrown by `await broadcasterResult.wait()` is not caught/forwarded to `fail()`, so the outer `Promise` can remain pending forever.
## Issue Context
`BroadcasterResult.wait()` awaits `Promise.all(...)`, which rejects if any subscriber promise rejects. Because the native API ignores the handler’s returned promise, those rejections won’t naturally propagate to the outer promise.
## Fix Focus Areas
- src/driver/nativescript/NativescriptQueryRunner.ts[72-146]
## Suggested fix
Wrap the handler body (including `await broadcasterResult.wait()`) in a try/catch that always settles the outer promise, e.g.:
- Keep `handler` non-async and drive settling via `.then/.catch`, OR
- Use an async IIFE and explicitly catch:

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



Remediation recommended
2. Sync subscriber masks error 🐞 Bug ☼ Reliability ⭐ New
Description
In CapacitorQueryRunner.query()’s catch block, broadcastAfterQueryEvent() is invoked outside the
try/catch that only guards broadcasterResult.wait(), so a synchronous throw from an afterQuery
subscriber can escape and replace the original database error. This defeats the intended behavior of
preserving the original query failure when broadcasting afterQuery on errors.
Code

src/driver/capacitor/CapacitorQueryRunner.ts[R106-114]

+            this.broadcaster.broadcastAfterQueryEvent(
+                broadcasterResult,
+                query,
+                parameters,
+                false,
+                undefined,
+                undefined,
+                err,
+            )
Evidence
Capacitor’s catch block only protects broadcasterResult.wait(); since broadcastAfterQueryEvent()
invokes subscriber.afterQuery() without a try/catch, a synchronous subscriber throw will propagate
and prevent throwing QueryFailedError for the original query failure.

src/driver/capacitor/CapacitorQueryRunner.ts[99-122]
src/subscriber/Broadcaster.ts[499-528]

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

## Issue description
In `CapacitorQueryRunner.query()`’s error path, `broadcastAfterQueryEvent(...)` can throw synchronously (e.g., a subscriber throws before returning), which bypasses the intended `QueryFailedError` and masks the original query error.

## Issue Context
`Broadcaster.broadcastAfterQueryEvent` calls `subscriber.afterQuery(...)` directly and does not wrap subscriber execution in a try/catch, so synchronous throws propagate to the caller.

## Fix Focus Areas
- src/driver/capacitor/CapacitorQueryRunner.ts[99-121]
- src/subscriber/Broadcaster.ts[499-528]

## Suggested fix
Wrap both the `broadcastAfterQueryEvent(...)` call *and* the subsequent `await broadcasterResult.wait()` in a single try/catch in the query failure path, swallowing subscriber errors so the original query error is always rethrown as `QueryFailedError`.

Example shape:
```ts
try {
 this.broadcaster.broadcastAfterQueryEvent(...)
 await broadcasterResult.wait()
} catch {
 // a subscriber failing must not hide the original query error
}
throw new QueryFailedError(query, parameters, err)
```

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


3. any types in test ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new unit test disables no-explicit-any and uses any for driver/dataSource stubs, which
weakens type-safety and can hide real contract mismatches. This conflicts with the guideline to
avoid any usage added to bypass type issues.
Code

test/unit/driver/query-broadcast-events.test.ts[R1-18]

+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { expect } from "chai"
+import { CapacitorQueryRunner } from "../../../src/driver/capacitor/CapacitorQueryRunner"
+import { NativescriptQueryRunner } from "../../../src/driver/nativescript/NativescriptQueryRunner"
+
+function delay(ms: number): Promise<void> {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/**
+ * A minimal DataSource stub with a single subscriber whose afterQuery hook
+ * does real async work, so tests can tell whether query() waited for it.
+ */
+function makeDataSource() {
+    let subscriberSettled = false
+    const dataSource: any = {
+        logger: { logQuery() {}, logQueryError() {}, logQuerySlow() {} },
+        manager: {},
Evidence
PR Compliance ID 4 forbids introducing any casts/usage to bypass type issues. The added test file
explicitly disables the no-explicit-any rule and defines dataSource/driver as any, meeting
the failure criteria.

Rule 4: Remove AI-generated noise
test/unit/driver/query-broadcast-events.test.ts[1-27]

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 unit test introduces `/* eslint-disable @typescript-eslint/no-explicit-any */` and multiple `any`-typed stubs, which reduces maintainability and may mask type regressions.
## Issue Context
The compliance checklist asks to avoid AI-generated noise patterns such as `any` usage to bypass types. Even in tests, minimal typing (or `unknown` + narrowing) improves correctness and future refactors.
## Fix Focus Areas
- test/unit/driver/query-broadcast-events.test.ts[1-31]

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


Results up to commit e68c368


🐞 Bugs (1) 📘 Rule violations (1) 📜 Skill insights (0)


Action required
1. Async callback can hang 🐞 Bug ☼ Reliability
Description
In NativescriptQueryRunner.query(), the native callback handler is now async and awaits
broadcasterResult.wait(); if any afterQuery subscriber promise rejects, the handler throws/rejects
but nothing catches it, so ok()/fail() is never called and the query() Promise can remain pending
indefinitely.
Code

src/driver/nativescript/NativescriptQueryRunner.ts[R101-112]

+                    this.broadcaster.broadcastAfterQueryEvent(
+                        broadcasterResult,
+                        query,
+                        parameters,
+                        false,
+                        undefined,
+                        undefined,
+                        err,
+                    )
+                    await broadcasterResult.wait()
                    fail(new QueryFailedError(query, parameters, err))
+                    return
Evidence
The handler awaits BroadcasterResult.wait() before calling ok()/fail(), but since it is used as a
callback the returned promise is ignored; if wait() rejects, control exits before ok()/fail() and
the outer promise is left pending. BroadcasterResult.wait() uses Promise.all, so a rejecting
subscriber promise will reject wait().

src/driver/nativescript/NativescriptQueryRunner.ts[72-146]
src/subscriber/Broadcaster.ts[499-528]
src/subscriber/BroadcasterResult.ts[15-24]

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

## Issue description
`NativescriptQueryRunner.query()` passes an `async` handler to callback-style native APIs (`databaseConnection.all/execSQL`). Any rejection thrown by `await broadcasterResult.wait()` is not caught/forwarded to `fail()`, so the outer `Promise` can remain pending forever.

## Issue Context
`BroadcasterResult.wait()` awaits `Promise.all(...)`, which rejects if any subscriber promise rejects. Because the native API ignores the handler’s returned promise, those rejections won’t naturally propagate to the outer promise.

## Fix Focus Areas
- src/driver/nativescript/NativescriptQueryRunner.ts[72-146]

## Suggested fix
Wrap the handler body (including `await broadcasterResult.wait()`) in a try/catch that always settles the outer promise, e.g.:

- Keep `handler` non-async and drive settling via `.then/.catch`, OR
- Use an async IIFE and explicitly catch:

```ts
const handler = (err: any, raw: any) => {
 void (async () => {
   // existing body, including await broadcasterResult.wait()
 })().catch((e) => {
   fail(e) // or fail(new QueryFailedError(query, parameters, e)) depending on desired semantics
 })
}
```

Also ensure you never call `ok/fail` twice (optionally guard with a `settled` flag).

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



Remediation recommended
2. any types in test 📘 Rule violation ⚙ Maintainability
Description
The new unit test disables no-explicit-any and uses any for driver/dataSource stubs, which
weakens type-safety and can hide real contract mismatches. This conflicts with the guideline to
avoid any usage added to bypass type issues.
Code

test/unit/driver/query-broadcast-events.test.ts[R1-18]

+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { expect } from "chai"
+import { CapacitorQueryRunner } from "../../../src/driver/capacitor/CapacitorQueryRunner"
+import { NativescriptQueryRunner } from "../../../src/driver/nativescript/NativescriptQueryRunner"
+
+function delay(ms: number): Promise<void> {
+    return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/**
+ * A minimal DataSource stub with a single subscriber whose afterQuery hook
+ * does real async work, so tests can tell whether query() waited for it.
+ */
+function makeDataSource() {
+    let subscriberSettled = false
+    const dataSource: any = {
+        logger: { logQuery() {}, logQueryError() {}, logQuerySlow() {} },
+        manager: {},
Evidence
PR Compliance ID 4 forbids introducing any casts/usage to bypass type issues. The added test file
explicitly disables the no-explicit-any rule and defines dataSource/driver as any, meeting
the failure criteria.

Rule 4: Remove AI-generated noise
test/unit/driver/query-broadcast-events.test.ts[1-27]

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 unit test introduces `/* eslint-disable @typescript-eslint/no-explicit-any */` and multiple `any`-typed stubs, which reduces maintainability and may mask type regressions.

## Issue Context
The compliance checklist asks to avoid AI-generated noise patterns such as `any` usage to bypass types. Even in tests, minimal typing (or `unknown` + narrowing) improves correctness and future refactors.

## Fix Focus Areas
- test/unit/driver/query-broadcast-events.test.ts[1-31]

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


Grey Divider

Qodo Logo

@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

…vers

The Capacitor and NativeScript query runners never emitted the
`beforeQuery`/`afterQuery` subscriber events, so subscribers registered
through those two drivers were never invoked, unlike every other SQLite
family driver (better-sqlite3, cordova, expo, sqljs, react-native).

Add the broadcasts to each driver's `query()` mirroring the existing
sibling drivers. In NativeScript the native call is callback based, so
`broadcasterResult.wait()` is awaited inside the callback right before
resolving or rejecting, ensuring async subscribers settle before the
query promise does, on both the success and failure paths. The failure
branch also gains a missing `return` so a failed query no longer falls
through and emits a spurious success event.
Both runners await the afterQuery broadcaster result from inside a
callback (NativeScript) or after the awaited native call (Capacitor). A
rejecting subscriber previously left the NativeScript query promise
pending forever, and on Capacitor a subscriber rejection on the error
path superseded the original query error via the trailing finally.

Await the broadcaster result explicitly on each path: on the error path
the subscriber rejection is swallowed so the original QueryFailedError is
preserved, and on the success path it propagates as the query's own
rejection. Both drivers now behave consistently. Also drop the any casts
and the eslint-disable from the new test.
@kyungseopk1m
kyungseopk1m force-pushed the fix/capacitor-nativescript-query-broadcast branch from 536ea9b to f5c451a Compare September 20, 2026 15:19

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-triage PR needs issue link triage

Development

Successfully merging this pull request may close these issues.

2 participants