Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ jobs:
- name: Run go vet
run: GOOS=js GOARCH=wasm go vet ./...

# The Node storage backend is invisible to every other job here: `compile`
# runs a host build, so the driver test's `js && wasm` tag excludes it, and
# the Playwright job matches only *.spec.js. Without this job the VFS, its
# test suite, and the Go driver tests under Node would all sit behind a green
# board that never runs them.
node-test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22

- name: Run Node storage backend tests
run: make node-test

browser-test:
runs-on: ubuntu-latest
steps:
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

- Added a Node storage backend: the `nodefs` VFS in `bridge/sqlite-node-vfs.js`, a `node:worker_threads` path in the bridge, and Node-aware script and wasm loading in the worker.
- Tightened the memory fallback: naming a durable VFS that cannot be opened is now an error rather than a silent `:memory:` substitution. Only `vfs=auto` without `require_persistent` may fall back.
- Added `sqliteBridge.shutdown()` so a Node host can retire the worker thread and let its process exit.
- Fixed pragma ordering at open, which made `journal_mode=WAL` unreachable on every VFS this driver offers. None of them implements `xShmMap`, so WAL is only available through SQLite's "WAL without shared memory" mode, which is conditional on `locking_mode=EXCLUSIVE`. Any `locking_mode` pragma is now applied first, and the journal mode last. Without the first half, reopening an existing WAL database failed with `SQLITE_CANTOPEN` on whichever pragma happened to read a page (`auto_vacuum`, for instance); without the second, a WAL request silently produced a rollback journal.
- A pragma that fails at open now reports which pragma it was.
- The effective `journal_mode` is read back after it is set, and a mismatch is an error. SQLite answers a journal mode it cannot honor by leaving the database in its previous mode, so a caller that asked for WAL could otherwise run on the rollback journal, where `synchronous=NORMAL` means something considerably weaker.

- Replaced SQLite Worker1/Promiser runtime usage with a dedicated `sqlite3.oo1` Worker.
- Added browser E2E coverage for OPFS, memory mode, transactions, BLOBs, dump/load, migrations, generated SQL shapes, named parameters, context cancellation, and storage behavior.
- Updated SQLite WASM assets to 3.53.1 / 3530100.
Expand Down
10 changes: 9 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,15 @@ SQLite WASM uses these browser runtime files:
- `Cross-Origin-Embedder-Policy: require-corp`

### VFS Fallback
If OPFS unavailable, automatically falls back to in-memory storage.
Only `vfs=auto` falls back to in-memory storage, and only when
`require_persistent` is not set. An explicitly named durable VFS (`opfs`,
`opfs-wl`, `opfs-sahpool`, `nodefs`) that cannot be opened is an error.

### Node hosts
`bridge/sqlite-node-vfs.js` provides the `nodefs` VFS over the synchronous
`node:fs` API, and the bridge spawns the worker through `node:worker_threads`
instead of the browser `Worker`. Run `make node-test` (or
`node --test tests/node-backend.test.cjs`) for that path.

### database/sql Integration
Example uses database/sql code in `example/generated/`:
Expand Down
16 changes: 15 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ build-example: fetch-assets build-wasm
@echo "📦 Copying bridge and assets to example..."
cp bridge/sqlite-bridge.js example/
cp bridge/sqlite-worker.js example/
cp bridge/sqlite-node-vfs.js example/
cp assets/*.js example/
cp assets/*.wasm example/
@echo "✅ Example built"
Expand All @@ -42,12 +43,24 @@ serve: build-example
cd example && node server.js

# Run tests
test:
test: node-test
@echo "🧪 Running tests..."
go test -v ./...
@echo "✅ Tests passed"
@echo "ℹ️ Run make browser-test for headless Chrome E2E coverage"

# Run the Node storage backend tests: the JS bridge/VFS suite, then the Go
# driver itself under Node. This deliberately does not depend on fetch-assets,
# because the committed assets pin a SQLite version that re-fetching would
# silently move.
node-test:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 major — No CI job runs any of this. node-test is wired into make test, but .github/workflows/ci.yml never invokes make test — the compile job runs go test -v ./... directly (a host build, so driver_node_js_wasm_test.go is excluded by its js && wasm tag), browser-test runs make browser-test, and playwright-test runs npm test. This PR also adds testMatch: "**/*.spec.js" to playwright.config.js, which explicitly excludes tests/node-backend.test.cjs from the Playwright job.

Net: the 606-line sqlite-node-vfs.js, the 553-line tests/node-backend.test.cjs, and the 293-line driver_node_js_wasm_test.go are covered by a green board that never executes them. For the storage layer under a wallet key store, a green CI that does not run it is worse than no CI, because it reads as coverage.

Both suites do pass locally — node --test tests/node-backend.test.cjs (19/19) and GOOS=js GOARCH=wasm go test -exec "node scripts/node-wasm-test-exec.cjs" -run TestNodeDriver ./ (5/5) — so this is a wiring gap, not a broken harness. Please add a node-test job to ci.yml in this PR (setup-node + make node-test) so the next change to the VFS is caught by the board rather than by a wallet.

@echo "🧪 Running Node storage backend tests..."
node --test tests/node-backend.test.cjs
@echo "🧪 Running Go driver tests under Node..."
GOOS=js GOARCH=wasm go test \
-exec "node scripts/node-wasm-test-exec.cjs" \
-run TestNodeDriver -v ./

browser-test: build-example
@echo "🌐 Running browser E2E tests..."
WASM_BROWSER_TEST=1 go test -run TestBrowserE2E ./...
Expand Down Expand Up @@ -94,6 +107,7 @@ help:
@echo " make build-example- Build example only"
@echo " make serve - Build and serve the demo locally"
@echo " make test - Run tests"
@echo " make node-test - Run Node storage backend tests"
@echo " make browser-test - Run headless Chrome browser E2E tests"
@echo " make playwright-test - Run Playwright browser tests against the example page"
@echo " make clean - Clean build artifacts"
Expand Down
37 changes: 32 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# go-wasmsqlite

A WebAssembly SQLite driver for Go. It lets browser-based Go WASM applications use the standard `database/sql` API with SQLite running entirely client-side and persisting to OPFS when the browser supports it.
A WebAssembly SQLite driver for Go. It lets Go WASM applications use the standard `database/sql` API with SQLite running entirely in-process: persisting to OPFS in a browser, and to the host filesystem under Node.

## Current Architecture

Expand All @@ -11,18 +11,45 @@ Go App (WASM)
-> database/sql driver ("wasmsqlite")
-> syscall/js adapter
-> sqlite-bridge.js RPC client on the main thread
-> sqlite-worker.js dedicated Worker
-> sqlite-worker.js dedicated worker
-> sqlite3.oo1.DB / sqlite3.oo1.OpfsDb
-> SQLite WASM + OPFS storage
-> SQLite WASM + OPFS storage (browser)
-> SQLite WASM + node:fs VFS (Node)
```

`sqlite-worker.js` imports `sqlite3.js`, calls `sqlite3InitModule()`, opens databases with an automatic OPFS preference order by default (`opfs-wl`, `opfs-sahpool`, then `opfs`), and falls back to `:memory:` only when memory fallback is allowed. SQLite still runs in a Worker because OPFS requires worker-side file APIs.
`sqlite-worker.js` loads `sqlite3.js`, calls `sqlite3InitModule()`, and opens databases through the best durable VFS the host offers.

In a browser it imports the script, spawns a Web Worker, and prefers `opfs-wl`, then `opfs-sahpool`, then `opfs`. Under Node it requires the script, spawns a `node:worker_threads` worker, and uses the `nodefs` VFS from `sqlite-node-vfs.js`, which maps SQLite's file operations onto the synchronous `node:fs` API. SQLite runs in a worker on both hosts, in a browser because OPFS needs worker-side file APIs and under Node so that a busy database cannot stall the host's event loop.

### Durable means durable

Naming a durable VFS (`opfs`, `opfs-wl`, `opfs-sahpool`, or `nodefs`) is a promise the worker keeps or breaks loudly. If that VFS cannot be opened, the open fails; it never quietly returns an in-memory database instead. Only `vfs=auto` may settle for memory, and even then not when `require_persistent=true` is set. This matters for anything whose database is the only copy of its state, such as a wallet, where silently running against storage that evaporates on exit loses data that cannot be recovered from anywhere else.

### Node hosts

Under Node the host must give Go's `wasm_exec.js` a real filesystem before instantiating the WASM module, and must tell the bridge where the runtime assets live:

```js
globalThis.fs = require("node:fs"); // else wasm_exec.js stubs fs with ENOSYS
globalThis.sqliteBridgeAssetDir = wasmDir; // holds sqlite3.js, sqlite3.wasm, sqlite-worker.js, sqlite-node-vfs.js
```

Two Node processes must not write one database. The `nodefs` VFS enforces that with a pid-stamped lock file taken alongside each main database opened for writing; a lock whose owning process is gone is reclaimed automatically, so a crash does not strand the database. A second process attempting the same database fails to open, and the error names the pid holding it.

The lock file sits next to the database as `<database>-nodefs-lock`. Deleting it by hand is the recovery if a database is ever stranded behind a lock the VFS declines to reclaim, and is safe exactly when no process is using that database.

Node core exposes neither `flock` nor `fcntl`, so this is a lock file rather than a kernel lock, and it is worth knowing where that falls short of the real thing:

- **Writers only.** A read-only open takes no lock and is not blocked by one. A reader running against a live writer sees confusing errors or stale data rather than silent damage, but it is not excluded.
- **One pid namespace, one machine.** Two containers sharing a bind-mounted data directory number their processes independently, so each reads the other's lock as belonging to a process that does not exist and both proceed. Over NFS or SMB neither the atomicity nor the pid check holds. Do not point two containers or two hosts at one database directory.
- **Recycled pids are handled.** The lock records the owner's kernel start time where the platform exposes it (Linux), so a reused pid number does not read as the original owner and strand the database.

## Features

- Standard `database/sql` driver named `wasmsqlite`
- OPFS persistence in supported browsers
- In-memory fallback when OPFS is unavailable
- Host filesystem persistence under Node through the `nodefs` VFS
- In-memory fallback only when no durable VFS was requested
- Transactions through `BEGIN IMMEDIATE`, `COMMIT`, and `ROLLBACK`
- BLOB round trips through `[]byte`
- Database dump/load helpers with BLOB-safe SQL literals
Expand Down
96 changes: 95 additions & 1 deletion bridge/sqlite-bridge.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
// Main-thread bridge between Go WASM and the dedicated SQLite oo1 worker.
//
// The worker is a browser Web Worker in a browser and a node:worker_threads
// worker under Node. The two APIs disagree on nearly everything at the seam
// (construction, event delivery, teardown), so the Node side is wrapped in an
// adapter that presents the browser Worker shape and the rest of this file
// stays host-independent.

(() => {
const bridgeProtocolVersion = 1;
Expand All @@ -9,17 +15,82 @@
const pending = new Map();
const bridgeScriptURL = globalThis.document?.currentScript?.src || "";

// isNodeHost reports whether this is Node rather than a browser. Node has no
// global Worker constructor, which is both the thing that distinguishes it
// and the exact reason the adapter below has to exist.
const isNodeHost =
typeof globalThis.process === "object" &&
!!globalThis.process?.versions?.node &&
typeof globalThis.Worker !== "function";

function workerURL(override) {
if (override) return override;
if (globalThis.sqliteBridgeWorkerURL) return globalThis.sqliteBridgeWorkerURL;
if (bridgeScriptURL) return new URL("sqlite-worker.js", bridgeScriptURL).href;
return "sqlite-worker.js";
}

// nodeAssetDir resolves the directory holding the runtime assets. A host
// that evaluates this file as a string (which is how a Go WASM host usually
// loads it) has no __dirname, so sqliteBridgeAssetDir is the supported knob.
function nodeAssetDir() {
const nodePath = require("node:path");
if (globalThis.sqliteBridgeAssetDir) {
return nodePath.resolve(globalThis.sqliteBridgeAssetDir);
}
if (typeof __dirname === "string") return __dirname;
return process.cwd();
}

// createNodeWorker starts the worker under node:worker_threads and adapts it
// to the browser Worker interface this bridge is written against.
//
// The worker source is read and evaluated rather than being handed to Node
// as a path, because a path is interpreted through the nearest package.json:
// a ".js" file that lands inside a "type": "module" package would be loaded
// as ESM and its require() calls would fail. Evaluating the source sidesteps
// the question entirely, since an eval'd worker is always CommonJS.
function createNodeWorker(override) {
const { Worker: NodeWorker } = require("node:worker_threads");
const nodeFS = require("node:fs");
const nodePath = require("node:path");

const assetDir = nodeAssetDir();
const scriptPath = override
? nodePath.resolve(assetDir, override)
: nodePath.join(assetDir, "sqlite-worker.js");

let source;
try {
source = nodeFS.readFileSync(scriptPath, "utf8");
} catch (error) {
throw new Error(
`unable to read sqlite-worker.js at ${scriptPath}: ${error.message}; ` +
"set globalThis.sqliteBridgeAssetDir to the runtime asset directory"
);
}

const nodeWorker = new NodeWorker(source, {
eval: true,
workerData: { assetDir: nodePath.dirname(scriptPath) },
});

const adapter = {
onmessage: null,
onerror: null,
postMessage: (message) => nodeWorker.postMessage(message),
terminate: () => nodeWorker.terminate(),
};
nodeWorker.on("message", (data) => adapter.onmessage?.({ data }));
nodeWorker.on("error", (error) => adapter.onerror?.(error));

return adapter;
}

function ensureWorker(override) {
if (worker) return;

worker = new Worker(workerURL(override));
worker = isNodeHost ? createNodeWorker(override) : new Worker(workerURL(override));
worker.onmessage = (event) => {
const message = event.data || {};
const waiter = pending.get(message.id);
Expand Down Expand Up @@ -58,6 +129,9 @@
if (!initPromise) {
initPromise = request("init", {
sqliteJSURL: options.sqliteJSURL || globalThis.sqliteBridgeSQLiteJSURL || "",
// rootDir anchors relative database names for the node:fs VFS. It is
// ignored in a browser, where names are origin-local OPFS paths.
rootDir: options.rootDir || globalThis.sqliteBridgeRootDir || "",
expectedBridgeProtocolVersion: bridgeProtocolVersion
}).then((result) => {
if (result.workerProtocolVersion !== expectedWorkerProtocolVersion) {
Expand Down Expand Up @@ -141,6 +215,26 @@
async load(dbId, sql) {
await request("load", { dbId, sql });
return { ok: true };
},

// shutdown tears the worker down. A browser page discards its workers when
// it unloads, but a Node worker thread keeps the host process alive, so a
// short-lived Node program needs a way to say it is finished. Databases
// should be closed first; this does not flush anything on their behalf.
async shutdown() {
if (!worker) return { ok: true };

const stopping = worker;
worker = null;
initPromise = null;
for (const waiter of pending.values()) {
waiter.reject(new Error("sqlite worker shut down"));
}
pending.clear();
if (typeof stopping.terminate === "function") {
await stopping.terminate();
}
return { ok: true };
}
};
})();
Loading
Loading