Skip to content

feat: add bun-sqlite driver (bun built-in sqlite module) - #12691

Open
trashhead wants to merge 3 commits into
typeorm:masterfrom
trashhead:feature/bunsqlite
Open

trashhead wants to merge 3 commits into
typeorm:masterfrom
trashhead:feature/bunsqlite

Conversation

@trashhead

Copy link
Copy Markdown

Description of change

Adds a new bun-sqlite driver that uses Bun's built-in bun:sqlite module.

Why this is needed

The existing better-sqlite3 driver requires compiling a native Node.js addon (better_sqlite3.node), which fails in environments without build tools (MSVC on Windows, node-gyp on Linux/macOS). The Bun runtime ships SQLite as a first-class built-in — no native compilation, no extra dependencies.

What was added

  • BunSqliteDriver.ts — driver extending AbstractSqliteDriver
  • BunSqliteQueryRunner.ts — query runner extending AbstractSqliteQueryRunner
  • BunSqliteDataSourceOptions.ts — type: "bun-sqlite" options type
  • DriverFactory.ts — registered the new driver
  • DriverUtils.ts — added "bun-sqlite" to isSQLiteFamily() (required so TypeORM uses NULL instead of unsupported DEFAULT in SQLite INSERT statements)
  • DatabaseType.ts — added "bun-sqlite" to the union
  • DataSourceOptions.ts — added BunSqliteDataSourceOptions to the union
  • PlatformTools.ts — added "bun:sqlite" case to load()
  • ormconfig.sample.json — added bun-sqlite entry with skip: true (opt-in; requires Bun runtime)
  • DEVELOPER.md — added instructions for running bun-sqlite tests

Key implementation differences from better-sqlite3

better-sqlite3 bun:sqlite
stmt.reader stmt.columnNames.length > 0
db.pragma("key = val") db.prepare("PRAGMA key = val").run()
db.pragma("key") → array db.prepare("PRAGMA key").all()

How it was verified

51 tests passing under the Bun runtime, covering: WAL mode, column types, generated columns, views, UUID generation, JSON/JSONB, transactions, query builder, schema builder, SQL tags, bulk saves, and more. See DEVELOPER.md for how to run them.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword: Fixes How can support bun native sqlite drive? #11236
  • There are new or updated tests validating the change (test/functional/driver/bun-sqlite/*.test.ts)
  • Documentation has been updated to reflect this change (DEVELOPER.md)

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider


Action required

1. Async query hooks ignored ⊘ Outdated
Description
BunSqliteQueryRunner.query() queues beforeQuery/afterQuery subscriber promises but never waits
for them, so SQL can execute before an async beforeQuery hook finishes and query() can resolve
before afterQuery hooks complete. Its failure path also omits the failed afterQuery event
entirely, breaking the query-subscriber lifecycle for this driver.
Code

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[R108-112]

Evidence
The Bun runner invokes event-specific broadcaster methods but never waits on BroadcasterResult;
the broadcaster implementation only queues subscriber promises. The existing Better SQLite runner
awaits the before event, emits success and failure after events, and waits in finally,
demonstrating the required lifecycle.

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[101-112]
src/driver/bun-sqlite/BunSqliteQueryRunner.ts[168-191]
src/subscriber/Broadcaster.ts[464-482]
src/subscriber/Broadcaster.ts[499-525]
src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[109-116]
src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[151-186]

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 Bun SQLite query runner does not await asynchronous query subscriber hooks and does not emit a failed `afterQuery` event.
## Issue Context
`Broadcaster` stores asynchronous hook results in `BroadcasterResult.promises`; callers must await them. Match the lifecycle behavior implemented by `BetterSqlite3QueryRunner`, including failure notification and a `finally` wait.
## Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteQueryRunner.ts[101-191]
- src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[102-186]

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


2. Relative attachments crash ⊘ Outdated
Description
For a programmatically constructed data source with a relative main database and an entity-level
relative database, getMainDatabasePath() passes undefined options.baseDirectory to
path.join(). Initialization then throws during entity metadata construction, so Bun SQLite cannot
use relative attached databases through the normal new DataSource(...) API.
Code

src/driver/bun-sqlite/BunSqliteDriver.ts[R197-200]

Evidence
Direct DataSource construction preserves the caller's options and the abstract driver copies them
without assigning baseDirectory, which is explicitly optional. Entity metadata calls the new
driver's buildTableName; for a relative attached database that reaches getMainDatabasePath() and
executes path.join(this.options.baseDirectory!, optionsDb), where the non-null assertion has no
runtime effect.

src/data-source/BaseDataSourceOptions.ts[161-165]
src/data-source/DataSource.ts[135-143]
src/driver/sqlite-abstract/AbstractSqliteDriver.ts[277-282]
src/metadata/EntityMetadata.ts[1072-1076]
src/driver/bun-sqlite/BunSqliteDriver.ts[90-105]
src/driver/bun-sqlite/BunSqliteDriver.ts[194-200]

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

## Issue description
Relative attached databases crash for direct `DataSource` construction because `baseDirectory` is optional and remains undefined outside `ConnectionOptionsReader`.
## Issue Context
Resolve a relative main database without assuming `baseDirectory` exists, using an appropriate current-directory fallback consistent with where the connection opens the main database. Add coverage using direct `new DataSource(...)` and an entity-level relative database.
## Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteDriver.ts[94-105]
- src/driver/bun-sqlite/BunSqliteDriver.ts[194-200]
- src/data-source/BaseDataSourceOptions.ts[161-165]

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


3. Wrong bun CLI path ⊘ Outdated
Description
InitCommand generates bun-sqlite projects with scripts.typeorm set to `bun
node_modules/typeorm/build/package/cli.js`, but the published TypeORM package exposes its CLI at the
package root (cli.js). This makes bun run typeorm fail in newly scaffolded bun-sqlite projects.
Code

src/commands/InitCommand.ts[R799-803]

Evidence
The init template hardcodes node_modules/typeorm/build/package/cli.js, but the repository's
package.json declares the CLI entrypoint as ./cli.js at the package root, and the gulp packaging
pipeline uses ./build/package only as a staging directory when building the distributable.
Therefore build/package/cli.js will not exist inside node_modules/typeorm/ for consumers.

src/commands/InitCommand.ts[799-803]
package.json[74-78]
gulpfile.ts[75-78]
gulpfile.ts[110-113]

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

## Issue description
For `bun-sqlite` projects, `typeorm init` generates a `package.json` script:
- `typeorm: "bun node_modules/typeorm/build/package/cli.js"`
However, `build/package` is TypeORM's internal *packaging output directory*, not a directory inside the installed npm package. In an installed dependency, the CLI entry is at the package root (`node_modules/typeorm/cli.js`, per the package's `bin` field).
### Issue Context
This breaks the main CLI script in the generated bun-sqlite scaffold (e.g., `bun run typeorm`).
### Fix Focus Areas
- src/commands/InitCommand.ts[799-803]
### Suggested fix
Change the generated script to a stable, published path, e.g.:
- `typeorm: "bun node_modules/typeorm/cli.js"`
(Alternatively, if you prefer relying on Bun tooling: `"bunx typeorm"`, but `node_modules/typeorm/cli.js` matches the package `bin` layout and avoids assuming `bunx`.)

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


View action required (4)
4. Init generates Node scripts ✓ Resolved
Description
InitCommand now allows selecting "bun-sqlite", but the generated README and package.json
scripts still instruct running via npm start / node / ts-node, which will execute under Node
and fail because BunSqliteDriver requires the Bun runtime. Users who follow the scaffolded
instructions will hit a runtime error during initialization/loading of bun:sqlite.
Code

src/commands/InitCommand.ts[R199-205]

Evidence
The init command now allows bun-sqlite, but the scaffolded README and start scripts still instruct
running via npm/node/ts-node; meanwhile the bun-sqlite driver throws unless bun:sqlite is
available (Bun runtime only).

src/commands/InitCommand.ts[691-709]
src/commands/InitCommand.ts[791-800]
src/driver/bun-sqlite/BunSqliteDriver.ts[150-162]

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

## Issue description
`typeorm init --database bun-sqlite` scaffolds a project whose README and `package.json` scripts assume Node/npm execution, but the `bun-sqlite` driver explicitly requires running under Bun. This mismatch leads to an immediate runtime failure if users follow the generated instructions.
## Issue Context
- The init flow was updated to accept `bun-sqlite` as a database option.
- The generated README still says `npm i` / `npm start`.
- The generated `start` script still uses `node --loader ts-node/esm ...` (ESM) or `ts-node ...` (CJS).
- `BunSqliteDriver` throws if `bun:sqlite` cannot be loaded (i.e., when running under Node).
## Fix Focus Areas
- src/commands/InitCommand.ts[691-709]
- src/commands/InitCommand.ts[720-800]
- src/commands/InitCommand.ts[61-88]
## What to change
1. Make the generated README instructions conditional on the selected database (or add a Bun-specific note when `database === "bun-sqlite"`). For example, for bun-sqlite use `bun install` and `bun run start` (or `bun src/index.ts`).
2. In `appendPackageJson(...)`, if `database === "bun-sqlite"`, generate a `start` script that runs the app with Bun (avoid `node ...` / `ts-node ...` commands that run under Node).
3. (Optional) Consider adjusting the `typeorm` script or adding documentation in the scaffold noting that TypeORM CLI commands may need Bun-compatible invocation when using `bun-sqlite`.

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


5. Missing bun-sqlite docs ✓ Resolved
Description
This PR adds a new public DataSourceOptions.type value (bun-sqlite), but the user docs listing
supported type values and SQLite driver docs do not mention it. Users may incorrectly assume
bun-sqlite is unsupported or be unable to configure it.
Code

src/driver/types/DatabaseType.ts[8]

Evidence
The PR adds "bun-sqlite" as a supported DatabaseType, which is user-facing configuration, but
the docs that enumerate supported type values still omit bun-sqlite and the SQLite driver page
only documents better-sqlite3 (and others). This fails the requirement that docs reflect public
API/usage changes.

Rule 2: Docs updated for user-facing changes
src/driver/types/DatabaseType.ts[5-11]
docs/docs/data-source/2-data-source-options.md[10-13]
docs/docs/drivers/sqlite.md[19-35]

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 user-facing database type (`type: "bun-sqlite"`) was added, but the public documentation does not list it as a supported `type` value and does not describe its SQLite driver options/runtime requirements.
## Issue Context
The PR introduces `bun-sqlite` as a first-class driver option, so docs should be updated where supported database `type` values and SQLite driver options are documented.
## Fix Focus Areas
- docs/docs/data-source/2-data-source-options.md[10-13]
- docs/docs/drivers/sqlite.md[1-35]
- docs/docs/data-source/4-data-source-api.md[146-148]

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


6. Relative DB path mismatch ✓ Resolved
Description
BunSqliteDriver opens/creates the database using the raw options.database string, but TypeORM’s
config loader only normalizes relative SQLite database paths for type: "better-sqlite3". This can
create the DB file/directories relative to the process working directory while other driver logic
(e.g., attached DB path resolution) treats the same path as relative to baseDirectory, leading to
DB files/ATTACH paths pointing at different locations.
Code

src/driver/bun-sqlite/BunSqliteDriver.ts[R117-132]

Evidence
The driver uses options.database directly for mkdir/open, but the config loader only rewrites
relative database paths for better-sqlite3, not bun-sqlite. Meanwhile
BunSqliteDriver.getMainDatabasePath() resolves relative paths using baseDirectory, creating an
internal inconsistency for relative paths.

src/driver/bun-sqlite/BunSqliteDriver.ts[117-148]
src/driver/bun-sqlite/BunSqliteDriver.ts[191-198]
src/connection/ConnectionOptionsReader.ts[187-200]

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

## Issue description
`bun-sqlite` currently uses `options.database` as-is when creating directories and opening the database, but the config normalization step that makes SQLite database paths relative to the config `baseDirectory` only runs for `better-sqlite3`. This can make `bun-sqlite` resolve relative paths against `process.cwd()` while other logic (e.g., `getMainDatabasePath()` used for ATTACH resolution) resolves them against `baseDirectory`.
### Issue Context
`ConnectionOptionsReader.normalizeConnectionOptions()` has a special-case for `better-sqlite3` only. `BunSqliteDriver` uses `path.dirname(this.options.database)` and `new this.sqlite(database, ...)` directly, but also computes main DB paths using `path.join(this.options.baseDirectory!, optionsDb)`.
### Fix Focus Areas
- src/connection/ConnectionOptionsReader.ts[187-200]
- src/driver/bun-sqlite/BunSqliteDriver.ts[117-132]
- src/driver/bun-sqlite/BunSqliteDriver.ts[191-197]
### Suggested fix
1. Extend `ConnectionOptionsReader`’s SQLite database path normalization to include `type: "bun-sqlite"` (same rules as `better-sqlite3`, including `":memory:"` exemption).
2. (Optional hardening) In `BunSqliteDriver.createDatabaseConnection()`, resolve `database` to an absolute (or baseDirectory-relative) path before mkdir/open when it is not absolute and not `":memory:"`, so programmatic DataSourceOptions behave consistently too.

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


7. Browser build mapping missing ✓ Resolved
Description
The new BunSqliteDriver imports Node-only modules (node:fs/promises, node:path) and depends on
bun:sqlite, but it is imported unconditionally by DriverFactory, which is pulled in by
DataSource. Unlike better-sqlite3, there is no package.json browser mapping and no dummy
export for BunSqliteDriver, so browser/React-Native builds that rely on these mappings can break
by bundling unsupported modules.
Code

src/driver/bun-sqlite/BunSqliteDriver.ts[R1-8]

Evidence
The new driver file clearly depends on Node/Bun-only modules, and it is imported by DriverFactory.
The project’s browser mapping/dummy mechanism currently covers better-sqlite3 but has no equivalent
entry/export for bun-sqlite, so browser builds that depend on these mappings won’t disable it.

src/driver/bun-sqlite/BunSqliteDriver.ts[1-8]
src/driver/DriverFactory.ts[1-7]
package.json[46-71]
src/platform/BrowserDisabledDriversDummy.template[71-86]

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

## Issue description
`bun-sqlite` is a Bun/Node-only driver but is now imported by `DriverFactory`, which is included in the main TypeORM entrypoints. The repository already has a browser build mechanism (package.json `browser` mappings + `BrowserDisabledDriversDummy`) to avoid bundling Node-only drivers, but `bun-sqlite` was not added to it.
### Issue Context
- `DriverFactory` imports `BunSqliteDriver` at module load time.
- `BunSqliteDriver` imports `node:*` modules.
- `package.json` has browser mappings for `better-sqlite3` but not `bun-sqlite`.
- The dummy template exports `BetterSqlite3Driver` but not `BunSqliteDriver`.
### Fix Focus Areas
- package.json[46-71]
- src/platform/BrowserDisabledDriversDummy.template[71-86]
### Suggested fix
1. Add a `browser` mapping entry for the compiled browser build path of bun-sqlite driver, analogous to better-sqlite3, e.g.:
- `./browser/driver/bun-sqlite/BunSqliteDriver.js`: `./browser/platform/BrowserDisabledDriversDummy.js`
(Optionally also map `BunSqliteQueryRunner.js` if it is ever imported directly.)
2. Update `BrowserDisabledDriversDummy.template` to export `class BunSqliteDriver {}` (and `BunSqliteQueryRunner {}` if you add the optional mapping), so the replacement module satisfies the expected exports.

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



Remediation recommended

8. Large generated IDs can fail inserts 🐞 Bug ≡ Correctness
Description
BunSqliteQueryRunner.query() returns lastInsertRowid unchanged even though the new statement
type permits a bigint. When that value is a bigint, SQLite's generated-key calculation subtracts a
number from it, throwing after the insert has executed.
Code

packages/typeorm/src/driver/bun-sqlite/BunSqliteQueryRunner.ts[149]

Evidence
The new statement contract allows a bigint row ID, the runner places it in the insert result, and
the shared generated-map path performs arithmetic on it with numeric operands.

packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[4-11]
packages/typeorm/src/driver/bun-sqlite/BunSqliteQueryRunner.ts[146-149]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[188-195]
packages/typeorm/src/driver/sqlite-abstract/AbstractSqliteDriver.ts[817-831]

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 bigint `lastInsertRowid` reaches generated-key arithmetic that mixes bigint and number, causing an insert to fail after execution.
## Fix Focus Areas
- packages/typeorm/src/driver/bun-sqlite/BunSqliteQueryRunner.ts[146-149]
- packages/typeorm/src/driver/sqlite-abstract/AbstractSqliteDriver.ts[817-831]
## Recommended Fix
Make generated-key calculation handle bigint results without mixed-type arithmetic or silently losing integer precision, and test an increment-generated key with a bigint row ID.

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


9. Failed initialization leaves a database open 🐞 Bug ☼ Reliability
Description
createDatabaseConnection() opens a Bun database and awaits prepareDatabase() before returning
the connection to the driver. If the callback or a subsequent pragma fails, the connection remains
local and unclosed because DataSource.initialize() does not disconnect a driver whose connect()
rejects.
Code

packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[R151-154]

Evidence
The connection is assigned to the driver only after creation resolves, while connect() is outside
the initialization cleanup block; the callback can reject before that assignment.

packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[140-164]
packages/typeorm/src/driver/sqlite-abstract/AbstractSqliteDriver.ts[296-302]
packages/typeorm/src/data-source/DataSource.ts[245-260]

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

## Issue description
An error after opening the Bun database but before returning it from `createDatabaseConnection()` leaves the open handle unreachable by normal driver cleanup.
## Fix Focus Areas
- packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[140-164]
## Recommended Fix
Wrap post-construction setup in a try/catch that closes the local database connection before rethrowing the original error. Test a rejecting `prepareDatabase` callback.

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


10. Scaffolded CLI script runs under Node, not Bun 🐞 Bug ≡ Correctness
Description
For bun-sqlite projects, InitCommand sets the generated typeorm script to bunx typeorm.
bunx follows the CLI's #!/usr/bin/env node shebang and starts a Node process, so `bun run
typeorm migration:run (and every other CLI command) will either fail to require("bun:sqlite")` or
fail to load the TypeScript src/data-source.ts.
Code

packages/typeorm/src/commands/InitCommand.ts[R800-804]

Evidence
Every TypeORM CLI entry point starts with a Node shebang. By default Bun respects that shebang under
bunx, so the CLI runs in Node, and BunSqliteDriver.loadDependencies throws "bun:sqlite is only
available in the Bun runtime". The scaffolded project also has no ts-node wiring in this branch, so
plain Node could not load the .ts data source either.

packages/typeorm/src/cli.ts[1-1]
packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[171-180]
packages/typeorm/src/commands/InitCommand.ts[800-811]

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 generated bun-sqlite project's `typeorm` script is `bunx typeorm`. That runs the CLI through its `#!/usr/bin/env node` shebang under Node, where `bun:sqlite` and the TS data source can't be loaded.
## Fix Focus Areas
- packages/typeorm/src/commands/InitCommand.ts[800-805]
## Recommended Fix
Change the script to `bunx --bun typeorm` (or `bun --bun node_modules/typeorm/cli.js`) so the CLI runs in the Bun runtime. That also lets it load `src/data-source.ts` without ts-node.

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


View review recommended (8)
11. Custom SQLite functions fail type checking 🐞 Bug ≡ Correctness
Description
BunSqliteDatabase exposes only prepare and close, so the prepareDatabase callback cannot
type-check calls that register a custom function or aggregate. This affects TypeScript users
configuring the documented callback through DataSourceOptions, even though the driver passes the
database object to it at runtime.
Code

packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[R14-17]

Evidence
The option promises function and aggregate registration, but its callback parameter is typed as an
interface containing only prepare and close. The options type is included in the public union,
and the driver invokes the callback with the database object.

packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[13-17]
packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[40-45]
packages/typeorm/src/data-source/DataSourceOptions.ts[24-27]
packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[140-154]

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 public `prepareDatabase` callback is typed with an interface that omits the methods needed to register custom SQLite functions and aggregates, despite documenting that use.
## Fix Focus Areas
- packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[13-17]
- packages/typeorm/src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[40-45]
## Recommended Fix
Extend the structural database type with accurate Bun SQLite registration methods, or use an available Bun database type, so documented callback usage type-checks.

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


12. Preparation errors escape handling ⊘ Outdated
Description
getStmt(query) runs before the try, so connection or SQL preparation failures escape as raw Bun
errors without logQueryError or QueryFailedError wrapping. Invalid SQL can therefore produce a
different public error contract and no query-error log compared with every execution failure caught
below.
Code

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[R115-117]

Evidence
getStmt calls connect() and prepare(), both of which can fail, but line 115 executes before
the catch that logs and wraps errors. The sibling Better SQLite runner deliberately performs the
same operation inside its protected block.

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[42-59]
src/driver/bun-sqlite/BunSqliteQueryRunner.ts[113-117]
src/driver/bun-sqlite/BunSqliteQueryRunner.ts[183-191]
src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[114-117]
src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[166-183]

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

## Issue description
Statement acquisition and preparation occur outside the query runner's error-handling block, bypassing TypeORM logging and error wrapping.
## Issue Context
Move `getStmt(query)` into the existing `try`, as done by `BetterSqlite3QueryRunner`, while retaining the corrected subscriber lifecycle.
## Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteQueryRunner.ts[113-191]
- src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[114-186]

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


13. Blob conversion misses rows ⊘ Outdated
Description
BunSqliteQueryRunner decides which result columns are blobs by inspecting only the first returned
row, so if the first row has NULL for a BLOB column, later rows can still contain Uint8Array values
that remain unconverted. This yields inconsistent types across rows and can break entity/test
expectations that blob columns hydrate as Buffer (e.g., Buffer.toString()).
Code

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[R124-128]

Evidence
The conversion logic derives blobKeys from raw[0], so a column with NULL in the first row is
never converted in later rows. Tests/entities model SQLite BLOB columns as Buffer and call
toString() on hydrated blob values, which depends on Buffer semantics.

src/driver/bun-sqlite/BunSqliteQueryRunner.ts[120-141]
test/functional/database-schema/column-types/sqlite/entity/Post.ts[56-70]
test/functional/database-schema/column-types/sqlite/column-types-sqlite.test.ts[31-91]

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

## Issue description
`BunSqliteQueryRunner.query()` detects “blob columns” using only `raw[0]`, then only converts those keys for all rows. If `raw[0][key]` is `null` (or otherwise not a `Uint8Array`) but later rows contain a `Uint8Array`, those later values remain unconverted.
### Issue Context
TypeORM’s SQLite tests/entities use `Buffer` for `blob` columns and rely on Buffer semantics (e.g., `blob.toString()` returning the original string), so returning a `Uint8Array` for some rows can break hydration/logic.
### Fix
Convert values based on per-cell runtime type, not just keys inferred from the first row. A simple, robust approach is:
- For each row in `raw`, iterate over its own keys and replace any `Uint8Array` value with `Buffer.from(value)`.
- (Optional) Keep a fast-path: if no `Uint8Array` is found in a row, skip conversion for that row.
### Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteQueryRunner.ts[120-141]

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


14. Bun tests silently pass ⊘ Outdated
Description
The new bun-sqlite test suites iterate with Promise.all(dataSources.map(...)), but when bun-sqlite
is skipped in ormconfig.json (the default) createTestingConnections returns an empty array and the
tests pass with zero assertions executed. This can make Node-based CI report green while bun-sqlite
coverage never runs.
Code

test/functional/driver/bun-sqlite/enable-wal.test.ts[R24-27]

Evidence
The bun-sqlite test uses enabledDrivers: ["bun-sqlite"] and then runs assertions only inside
dataSources.map(...), which does nothing when the array is empty. The test harness filters out
skipped connections and can return an empty list without error, allowing these tests to pass without
executing any assertions.

test/functional/driver/bun-sqlite/enable-wal.test.ts[10-31]
test/functional/driver/bun-sqlite/error-on-query-after-close.test.ts[10-30]
test/utils/test-utils.ts[230-247]
test/utils/test-utils.ts[374-383]

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 bun-sqlite test files can become silent no-ops when the bun-sqlite connection is skipped in `ormconfig.json` (default). In that case, `createTestingConnections()` returns `[]`, and `Promise.all(dataSources.map(...))` resolves immediately without running any assertions.
### Issue Context
`setupTestingConnections()` filters out configurations with `skip: true` before applying `enabledDrivers`, and `createTestingConnections()` does not fail when the resulting list is empty. This is fine for general multi-driver suites, but for driver-specific test files it hides missing coverage.
### Fix
In bun-sqlite-specific test suites, add an explicit guard so they *skip* (or fail loudly) when bun-sqlite isn’t actually runnable:
- In the `before()` hook, if `dataSources.length === 0`, call `this.skip()` with an explanation.
- Optionally also gate on Bun runtime detection (e.g., `process.versions?.bun`) and skip when not running under Bun.
### Fix Focus Areas
- test/functional/driver/bun-sqlite/enable-wal.test.ts[10-31]
- test/functional/driver/bun-sqlite/error-on-query-after-close.test.ts[10-30]
- test/utils/test-utils.ts[230-247]

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


15. Unescaped ATTACH filepath ⊘ Outdated
Description
BunSqliteDriver.attachDatabases() interpolates attachFilepathAbsolute directly into an ATTACH SQL
string without escaping embedded quotes, so a valid filepath containing '"' will produce invalid SQL
(and can become an injection surface if the path is attacker-controlled). This can break
initialization when attached databases are used.
Code

src/driver/bun-sqlite/BunSqliteDriver.ts[R188-190]

Evidence
The bun-sqlite driver constructs the ATTACH statement by directly interpolating the absolute
filepath into a quoted SQL string, without any escaping step. The codebase already has a standard
escaping utility for SQLite identifiers (escape()), highlighting that escaping is a recognized
concern but is not applied to the filepath in the new ATTACH logic.

src/driver/bun-sqlite/BunSqliteDriver.ts[181-191]
src/driver/sqlite-abstract/AbstractSqliteDriver.ts[547-554]

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

## Issue description
`BunSqliteDriver.attachDatabases()` builds an `ATTACH "${attachFilepathAbsolute}" AS "${attachHandle}"` SQL string using raw interpolation. If the filepath contains a double-quote character, the resulting SQL becomes syntactically invalid; additionally, if a filepath can be influenced by untrusted input, this becomes a SQL injection surface.
### Issue Context
TypeORM already provides identifier escaping via `AbstractSqliteDriver.escape()`, but that escaping is not used here, and the filepath is not escaped at all.
### Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteDriver.ts[181-191]
- src/driver/sqlite-abstract/AbstractSqliteDriver.ts[552-554]
### Suggested change
- Escape the attached database handle using `this.escape(attachHandle)`.
- Escape the filepath before interpolation (e.g., replace `"` with `""` if continuing to use double-quoted form), or switch to a safer quoting strategy consistently and escape accordingly.
- (Optional but recommended) Apply the same fix to the equivalent logic in the existing better-sqlite3 driver for consistency.

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


16. ATTACH mkdir('.') crash ✓ Resolved
Description
BunSqliteDriver avoids fs.mkdir(".") for the main database path (noted as a Bun ENOENT bug), but
attachDatabases() still calls createDatabaseDirectory(path.dirname(...)) without the same guard.
If an attached database resolves to the current directory (e.g., attaching a plain filename like
other.db), fs.mkdir(".") can still be executed and throw, breaking initialization/metadata
attach.
Code

src/driver/bun-sqlite/BunSqliteDriver.ts[R168-188]

Evidence
The driver already acknowledges a Bun bug where fs.promises.mkdir(".") throws ENOENT and adds a
guard for the main DB directory, but the attach flow still calls fs.mkdir() on path.dirname(...)
via createDatabaseDirectory() with no equivalent guard, so the same failure can still occur during
ATTACH.

src/driver/bun-sqlite/BunSqliteDriver.ts[117-125]
src/driver/bun-sqlite/BunSqliteDriver.ts[168-170]
src/driver/bun-sqlite/BunSqliteDriver.ts[178-188]

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

## Issue description
`BunSqliteDriver.createDatabaseConnection()` explicitly skips `fs.mkdir(".")` due to a Bun ENOENT bug, but the same workaround is not applied when attaching databases. `attachDatabases()` calls `createDatabaseDirectory(path.dirname(attachFilepathAbsolute))`, and `createDatabaseDirectory()` currently runs `fs.mkdir(dbPath)` unconditionally, which can still hit `dbPath === "."`.
### Issue Context
This is a Bun-runtime-only reliability bug that can appear when an attached database path has no directory component (so `path.dirname(...)` is `"."`). The driver already documents this exact Bun behavior for the main DB path, so the fix should be consistent across both code paths.
### Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteDriver.ts[117-125]
- src/driver/bun-sqlite/BunSqliteDriver.ts[168-170]
- src/driver/bun-sqlite/BunSqliteDriver.ts[178-188]
### Suggested change
Add the same `dbPath !== "."` (and optionally non-empty) guard inside `createDatabaseDirectory()` (or before calling it from `attachDatabases()`), so attached DBs in the current directory don’t trigger the Bun `mkdir(".")` failure.

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


17. any types in bun-sqlite ✓ Resolved
Description
The new bun-sqlite driver introduces multiple any types (e.g., prepareDatabase?: (db: any) and
stmtCache = new Map()), which weakens type safety and can hide API/usage errors. This violates the
requirement to avoid type-bypassing constructs and keep additions consistent with the project’s
typing standards.
Code

src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[29]

Evidence
PR Compliance ID 4 prohibits introducing type-bypassing noise like any casts/types. The new
bun-sqlite option surface and query runner use any in several added locations, reducing type
guarantees for both public API (prepareDatabase) and internal query execution paths.

Rule 4: Remove AI-generated noise
src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[29-29]
src/driver/bun-sqlite/BunSqliteQueryRunner.ts[39-40]
src/driver/bun-sqlite/BunSqliteQueryRunner.ts[123-133]

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 `bun-sqlite` code uses `any` for public option types and internal statement caching/row mapping, which reduces type safety and conflicts with the guideline to avoid type-bypassing constructs.
## Issue Context
`bun:sqlite` types may be awkward to import in Node contexts, but we can still avoid `any` by using `unknown`, minimal local interfaces/types (e.g., `BunSqliteDatabase`, `BunSqliteStatement`), or conditional `import type` patterns where supported.
## Fix Focus Areas
- src/driver/bun-sqlite/BunSqliteDataSourceOptions.ts[29-29]
- src/driver/bun-sqlite/BunSqliteQueryRunner.ts[39-40]
- src/driver/bun-sqlite/BunSqliteQueryRunner.ts[123-133]

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


18. Init CLI omits bun-sqlite ⊘ Outdated
Description
bun-sqlite is now a valid DatabaseType and is constructible via DriverFactory, but `typeorm
init --database still only allows better-sqlite3` for SQLite. As a result, users cannot scaffold a
Bun SQLite project via the init command (the option is rejected/not offered).
Code

src/driver/DriverFactory.ts[R42-43]

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

## Issue description
TypeORM's `InitCommand` hard-codes supported database choices and templates, but it wasn't updated to include the newly added `bun-sqlite` driver type. This makes `typeorm init` inconsistent with the now-supported `DatabaseType` union and `DriverFactory`.
## Issue Context
- `bun-sqlite` is a supported driver type in runtime code.
- The init command should either support scaffolding it (recommended) or intentionally document/guard against it.
## Fix Focus Areas
- Add `"bun-sqlite"` to the `--database` choices.
- Add a `case "bun-sqlite"` in the datasource template switch to emit a valid config.
- Ensure docker template and dependency injection logic handle `bun-sqlite` appropriately (likely same behavior as SQLite: no docker needed, no npm dependency required).
### Targeted code locations
- src/commands/InitCommand.ts[19-38]
- src/commands/InitCommand.ts[168-196]
- src/commands/InitCommand.ts[601-671]
- src/commands/InitCommand.ts[737-768]

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



Informational

19. Bun driver copies the better-sqlite3 driver 🐞 Bug ⚙ Maintainability ⭐ New
Description
BunSqliteDriver (including buildTableName, attachDatabases, getMainDatabasePath,
normalizeType, disconnect) and most of BunSqliteQueryRunner.query/getStmt are near-verbatim
copies of the BetterSqlite3Driver/BetterSqlite3QueryRunner code. A fix to one path, such as
ATTACH escaping, attach-path resolution or the query-subscriber lifecycle, won't reach the other, so
the two SQLite drivers will drift apart.
Code

packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[R200-203]

Evidence
The attach, table-name and path helpers in the Bun driver are the same as the better-sqlite3
versions. The only Bun-specific parts are how the connection is opened, the pragma calls and the
reader detection.

packages/typeorm/src/driver/better-sqlite3/BetterSqlite3Driver.ts[91-219]
packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[91-221]
packages/typeorm/src/driver/better-sqlite3/BetterSqlite3QueryRunner.ts[40-140]

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

## Issue description
BunSqliteDriver/BunSqliteQueryRunner copy most of BetterSqlite3Driver/BetterSqlite3QueryRunner, so a fix in one won't reach the other.

## Fix Focus Areas
- packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[91-221]
- packages/typeorm/src/driver/bun-sqlite/BunSqliteQueryRunner.ts[42-204]
- packages/typeorm/src/driver/better-sqlite3/BetterSqlite3Driver.ts[91-219]

## Recommended Fix
Move buildTableName, attachDatabases, getMainDatabasePath, createDatabaseDirectory and the statement cache/query skeleton into a shared base class or helper. Keep only the parts that differ in each driver: opening the connection, running pragmas and detecting whether a statement returns rows.

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


20. Read-only startup creates directories 🐞 Bug ≡ Correctness
Description
createDatabaseConnection() creates the parent directory before checking the readonly option.
Opening a missing database in read-only mode therefore leaves a new directory behind even though the
database cannot be created and initialization fails.
Code

packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[R124-129]

Evidence
Directory creation runs for every non-memory path, whereas readonly is only applied later when the
database is opened with create: !readonly.

packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[124-143]

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

## Issue description
Read-only initialization creates missing parent directories before attempting to open a database that cannot be created.
## Fix Focus Areas
- packages/typeorm/src/driver/bun-sqlite/BunSqliteDriver.ts[124-143]
## Recommended Fix
Only create the database directory when the connection is allowed to create a database. Test a read-only open against a missing nested path.

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

Grey Divider

⚠️ Warning | Comment size exceeded, inner finding content trimmed Learn more
⚠️ Warning | Comment size exceeded, non finding content trimmed Learn more

Grey Divider

Qodo Logo

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

1 similar comment
@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@trashhead trashhead changed the title Feature/bunsqlite feat: add bun-sqlite driver using Bun's built-in bun:sqlite module Jul 10, 2026
@trashhead trashhead changed the title feat: add bun-sqlite driver using Bun's built-in bun:sqlite module feat: add bun-sqlite driver using bun:sqlite built-in module Jul 10, 2026
@trashhead trashhead changed the title feat: add bun-sqlite driver using bun:sqlite built-in module feat: add bun-sqlite driver (bun built-in sqlite module) Jul 10, 2026
@trashhead

Copy link
Copy Markdown
Author

Not sure why qodo still references old code.
How do I trigger a new review?

@trashhead

Copy link
Copy Markdown
Author

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

@trashhead trashhead closed this Jul 11, 2026
@trashhead trashhead reopened this Jul 11, 2026
Comment thread package.json Outdated
@@ -51,6 +51,7 @@
"./browser/connection/options-reader/ConnectionOptionsYmlReader.js": "./browser/platform/BrowserConnectionOptionsReaderDummy.js",
"./browser/driver/aurora-data-api/AuroraDataApiDriver.js": "./browser/platform/BrowserDisabledDriversDummy.js",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

do we need a bunsqlite entry on BrowserDisabledDriversDummy.template?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Implemented

const raw = stmt
.all(...normalizedParameters)
.map((row: Record<string, unknown>) =>
Object.fromEntries(

@smith-xyz smith-xyz Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

isn't a stopper but this probably carries overhead on blob queries, not sure if we can do something like this to just skip when no blobs:

const raw = stmt.all(...normalizedParameters)
if (raw.length > 0) {
    const blobKeys = Object.keys(raw[0]).filter(
        (k) => raw[0][k] instanceof Uint8Array,
    )
    if (blobKeys.length > 0) {
        for (const row of raw) {
            for (const k of blobKeys) {
                if (row[k] instanceof Uint8Array) {
                    (row as any)[k] = Buffer.from(row[k] as Uint8Array)
                }
            }
        }
    }
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Optimized blob detections

path.dirname(attachFilepathAbsolute),
)
await this.dataSource.query(
`ATTACH "${attachFilepathAbsolute}" AS "${attachHandle}"`,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we probably need to safe guard this better from sqli - not a blocker, you're matching what better sqlite3 already does

@@ -2,13 +2,13 @@ import "chai/register-should"
import "source-map-support/register"
import "reflect-metadata"

import chai from "chai"
import { should, use } from "chai"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

is this for Bun compatibility?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes.
When running TypeORM's test suite with Bun as the JavaScript runtime, using a default import of chai causes a runtime crash:

TypeScript compiles import chai from "chai" into const chai_1 = require("chai") and then accesses chai_1.default. In Node.js this works because its CJS interop sets .default to the module exports. Bun's CJS interop does not — chai_1.default is undefined, so calling [chai_1.default.should()] throws immediately before any tests run:
TypeError: undefined is not an object (evaluating 'chai_1.default.should')]

The fix is to use named imports instead

@michaelbromley

Copy link
Copy Markdown
Member

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

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

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

Sorry for the disruption, and thanks for your patience.

This branch has not been deployed

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

Labels

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

How can support bun native sqlite drive?

3 participants