# Migrate From sqlite3 to better-sqlite3 in a Node.js API

Yes. An agent replaces the callback sqlite3 driver with better-sqlite3 in an Express API and proves each endpoint answers the same before and after.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-sqlite3-to-better-sqlite3/sqlite3/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the driver calls first, because the two libraries disagree on shape and not just on names. In an API like fraigo/node-express-rest-api-example there are two files to port. `database.js` opens `db.sqlite` with `new sqlite3.Database(path, callback)`, runs `CREATE TABLE user` inside the callback, and treats an error from that statement as the signal that the table already exists; otherwise it seeds two rows. `server.js` has five routes: `db.all` for the list, `db.get` for one user, and three `db.run` calls for insert, update and delete. Two of those use `function` callbacks so they can read `this.lastID` and `this.changes`. `package.json` asks for `sqlite3 ^4.2.0`, and the lockfile, still in `lockfileVersion` 1, resolves it to 4.2.0.

Then it tries to install, and here the migration stops being optional. On Node 22, `npm ci` looks for a prebuilt sqlite3 4.2.0 binary, gets a 403 from the download host, prints `Pre-built binaries not found for sqlite3@4.2.0 and node@22.23.4`, falls back to compiling with node-gyp, and fails. The project's README hints at the same pain from the other side: it lists Python 2.7 and Microsoft build tools as prerequisites on Windows. To get a baseline at all, the agent installs the newest sqlite3 5 release in a scratch copy, starts the server, and records the status and body of a fixed list of requests: both reads, a missing id, a non-numeric id, a valid insert, the same insert again, an insert with fields missing, three updates and two deletes.

The port replaces callbacks with return values. better-sqlite3 is synchronous, so `db.all(sql, params, cb)` becomes `db.prepare(sql).all(params)` inside `try` and `catch`, `this.lastID` becomes `info.lastInsertRowid`, and `this.changes` becomes `info.changes`. In `database.js` the agent stops using a failed `CREATE TABLE` as a test and asks `sqlite_master` whether the table exists. It also removes `nw-gyp` from the dependencies, which nothing in the two files requires, and leaves a note that `server.js` requires `body-parser` without declaring it, since that works only because Express installs it.

It repeats the recorded requests against the ported server and compares. One response differs. A duplicate email used to answer `400` with `SQLITE_CONSTRAINT: UNIQUE constraint failed: user.email`; it now answers `400` with `UNIQUE constraint failed: user.email`, because better-sqlite3 puts the code in `err.code` (`SQLITE_CONSTRAINT_UNIQUE`) and leaves it out of the message. Everything else matches, including answers a reviewer might not expect: a missing user returns `200` with `{"message":"success"}` and no `data` key in both versions, and an update that hits the unique constraint returns `400` with an empty object, because the handler sends `res.message` where it means `err.message`.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Replace the sqlite3 package with better-sqlite3 in this Node.js service. Read package.json, the lockfile, and every file that requires sqlite3. List each call (Database constructor, run, get, all, each, exec, serialize, prepare) and whether its callback reads this.lastID or this.changes. Run the lockfile install first and record whether it succeeds on the current Node version; if the native build fails, quote the lines that say why and take the baseline with the newest sqlite3 release that installs, in a scratch copy. Start the server on an empty database and record the status code and body for every route: success cases, a missing row, a malformed id, a constraint violation, missing fields, and a repeated delete. Port the code to better-sqlite3 with prepared statements and try/catch, keeping every status code and response shape. Do not fix handler bugs you find; list them. Remove dependencies the code no longer needs and regenerate the lockfile with the installed npm. Start the ported server on a fresh database, repeat the same requests, and show both sets of responses in the pull request with every difference explained. State the Node version the new driver requires.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that rewrites `database.js` and the five handlers in `server.js`, swaps the dependency in `package.json`, and replaces the lockfile with one in the current format. The description carries the failed `npm ci` output for the old driver, the request list with both sets of responses, and the single difference in the duplicate-email message. The repository's `test` script is still npm's placeholder that prints an error and exits 1, so there is no suite to run; the recorded requests are the evidence, and the agent says that plainly.

A reviewer weighs two things beyond the diff. The first is the engine floor: the current better-sqlite3 release declares `node >=22` in its `engines` field, so a deployment on an older Node needs an older release of the driver, and the prompt asks the agent to state that requirement. The second is the list of handler bugs the agent finds and does not fix, such as `res.message` in the update and delete error paths. They are real, they predate the port, and each is a one-line follow-up that is easier to review alone.

If any client matches on the old error text, the changed message is the place where this port could break a consumer. The description names the exact strings so that a search across client code takes a minute.

## Run it on every failed CI run on a Node upgrade branch

The usual moment this job appears is a Node version bump whose first CI run dies in a native build. Add an automation to the Project with a `github` trigger on `workflow_run.failure`, and save the prompt above with one more sentence: do the work only if the failing step is the sqlite3 build, and otherwise reply with what failed and change nothing. The failure is appended after the prompt as event text. Runs triggered from forks never fire.

For a known list of services, skip the trigger and start one run per repository through `POST /o/{org}/sessions`, each with a `request_id` that is a UUID v5 of the repository name.

## Why run it on Rush?

A driver swap in an API with no tests is judged by behaviour, and gathering that behaviour is tedious by hand: install two drivers, start two servers, send the same dozen requests twice, diff the bodies. The agent does this in a sandbox where a failed native build or a stray database file affects nothing else, and the transcript keeps each request and response, so the claim that only one message changed can be checked line by line.

It also separates what the migration changed from what was already wrong. Without a recorded baseline, a reviewer who notices that a missing user returns `200` would reasonably blame the new driver. With both outputs in the description, that conversation does not happen.

## Frequently asked questions

### Why does npm install fail on sqlite3 after a Node upgrade?

Old sqlite3 releases download a binary built for a specific Node ABI, and none was published for Node versions released years later. The install then falls back to compiling with node-gyp, which needs a C++ toolchain and often fails on old sources. The log line to look for is `Pre-built binaries not found`.

### Is it a problem that better-sqlite3 is synchronous?

Each query blocks the event loop while it executes, so a slow query delays other requests in the same process. For the small indexed lookups in an API like this one that is rarely measurable, and the code becomes plain `try` and `catch`. If you have long analytical queries, tell the agent and it reports which statements would need a worker thread.

### Does better-sqlite3 accept the same parameter values?

Mostly. Strings, numbers, bigints, buffers and `null` bind as before, and `undefined` binds as NULL, which this API's partial update relies on. A boolean does not: it raises `TypeError: SQLite3 can only bind numbers, strings, bigints, buffers, and null`, so the agent converts booleans to 0 and 1 where the old code passed them.

### Why not use the sqlite module built into Node?

It is an option on recent Node versions, but on Node 22 loading `node:sqlite` still prints an `ExperimentalWarning`. The agent ports to it instead if the prompt asks, and the request comparison works the same way.

### Is the original sqlite3 package still maintained?

Its GitHub repository, TryGhost/node-sqlite3, is archived. Releases newer than the one this lockfile pins do install on current Node, which is how the agent takes its baseline, but an archived driver is a reason to move while the change is small.

## More node-sqlite3 jobs

- [Fix "The Default Datetime Adapter Is Deprecated as of Python 3.12" in a sqlite3 App](https://getrush.ai/run/fix-sqlite3-default-datetime-adapter-deprecated-warning/sqlite3/)

## More jobs like this: Upgrade dependencies weekly

- [Replace golang.org/x/crypto/ssh/terminal With golang.org/x/term](https://getrush.ai/run/migrate-ssh-terminal-to-x-term/golang-x-crypto/)
- [Migrate a Rust CLI From structopt to clap 4 Derive](https://getrush.ai/run/migrate-structopt-to-clap/structopt/)
- [Upgrade Tailwind CSS v3 to v4](https://getrush.ai/run/migrate-tailwind-v4/tailwind/)
- [Migrate Tests From tape to the Node.js Test Runner (node:test)](https://getrush.ai/run/migrate-tape-to-node-test/tape/)
- [Migrate a Deno 1 App to Deno 2](https://getrush.ai/run/migrate-to-deno-2/deno/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
