Repository navigation
feat: SQLite compiled to wasm for Node and browsers - #2
Merged
Merged
Conversation
src/ moves to .mts (strict, NodeNext, .mts import specifiers rewritten on emit, erasableSyntaxOnly). tsup bundles src/index.mts, tsc checks types and emits .d.mts into types/, typescript-eslint lints *.mts, and coverage covers src/**/*.mts. The dev export condition carries only types and import; require always resolves to dist/index.cjs.
sqlite.version.json pins SQLite 3.54.1 (amalgamation URL + SHA3-256), wasi-sdk 34 and binaryen 133 (per-host tarballs + SHA-256). scripts/build-wasm.mjs downloads and verifies them into SQLITE_WASM_TOOLCHAIN_DIR (default .cache/toolchains/), compiles sqlite3.c + src/c/glue.c for wasm32-wasip1 (-O3 -flto, reactor), runs wasm-opt and writes dist/sqlite3.wasm, caching the result by its inputs. glue.c registers the default VFS "cldmv" in sqlite3_os_init and forwards every VFS and io method to the env.vfs_* imports (offsets as 32-bit halves, io methods version 1 with no xShm*). build is now tsup followed by build:wasm (tsup cleans dist/ first).
src/core/loader.mts compiles sqlite3.wasm lazily (no top-level await, so the require(esm) shim keeps working), checks its imports against what the loader provides, and instantiates it with the env.vfs_* imports bound to a JS driver. The only WASI import left is random_get. src/vfs/memory.mts keeps each file in a growable buffer and tracks lock levels per handle. File ids handed to drivers are process-wide, so one driver can serve several module instances. src/core/raw.mts (openRaw) opens a database and runs SQL; it is exported from the entry as an internal helper until the real Database API lands.
Covers sqlite_version() against sqlite.version.json, compile_options, FTS3/FTS4/FTS5, R*Tree, Geopoly, dbstat, math/JSON/percentile, WAL with exclusive locking on the memory driver, rollback journals, SQLITE_BUSY between two connections, the CJS shim opening a memory database, and 100% coverage of src/.
…ndle-size and pretest build
…de names glue.c gets the cb_* trampolines for scalar, aggregate and window functions and collations, with the callback id as user data. The build exports the backup, value and result functions the API needs. The loader wires the cb_* imports to a per-instance callback table and adds takeVfsError().
sqlite.open() with storage, readonly, create, journal, sync, foreign, timeout and bigint options; db.prepare/execute/pragma/transaction/fn/attach/detach/ backup/serialize/checkpoint/close; statement run/get/all/iterate with raw, pluck and expand; sqlite.error with code, number and sql. Storage drivers load through src/vfs/registry.mts; fs and opfs report that they aren't in this build until their modules land.
The registry now imports ./fs.mts and ./opfs.mts on first use. storage "auto" resolves to fs under Node and opfs in a dedicated worker, and fails with a clear sqlite.error anywhere else. Drivers get the full open options in prepare(), the router keys names by storage kind so two connections to one file can each bring a driver object, the OPFS driver takes its wait from the open's timeout and reports its errors as sqlite.error.
sqlite.open(path, { lock }) picks where the cross-process owner lock lives:
beside the database (default, falling back to the OS temp folder when the
lock folder can't be created), under the temp folder or a folder of your
own named by the SHA-256 of the file's real path, or as a row in a
_cldmv_lock table that detects a second process without preventing a
simultaneous one. The node-fs driver takes the folder locks in prepare()
without blocking the thread, db.info.lock reports the kind in effect, and
attachments and backup targets of a db-locked database use the folder lock.
Outside Node the loader fetches sqlite3.wasm with browser-loader.mts (compileStreaming); Node keeps reading it with node:fs. The runtime takes an override for the module source, which the worker host uses for its wasm option. tsup builds dist/host.mjs and dist/worker.mjs separately for the browser and swaps every node: module for a stub that throws when loaded, so those bundles contain no Node import (a test checks the built files). pretest and precoverage now run the whole build so dist/ exists for that check.
The worker host's connection is now the public API: engine.mts is a thin adapter over sqlite.open() and db.prepare() with a statement cache, and the host's own open-time pragmas and OPFS bookkeeping are gone (open, attach and detach go through the API and the driver registry; listen()'s root/locks/wait reach the OPFS driver as driver options). Errors on both sides are sqlite.error, rebuilt on the client from code, number and sql. New operations: backup, serialize (its buffer is transferred) and savepoint/release/revert for nested transactions, where a failure undoes only the savepoint. listen() takes a setup(db) hook that runs after open, for registering functions in the worker. Route releases now return a promise, so detach, a failed attach and the host's close wait until OPFS handles and locks are let go.
A transaction started while another runs on the client becomes a savepoint instead of waiting forever: a failure inside it undoes only the savepoint and the outer callback can catch it and go on. The client gains backup() and serialize() (the bytes come back transferred) and info.lock. db.fn.* throws an sqlite.error explaining that functions run in the worker and belong in the host's setup(db) hook.
npm test now ends with test:browser, which installs Playwright's chromium-headless-shell (no system packages needed on ubuntu-latest or in the k3s-test pod) and runs the OPFS and worker client tests in it.
The host always needs the OPFS driver, so listen() registers the bundled module instead of leaving it to a lazy import() on first open; that import broke inside workers under vitest's browser mode, which rewrites dynamic imports to a runner global workers don't have. Also covers the node-fs prepare() defaults and the OPFS driver's held() with Web Locks off.
Leader election over Web Locks, followers over a BroadcastChannel, and the handover rules: reads and unstarted writes are retried with the new leader, a write the old leader had started rejects with SQLITE_BUSY. db.info.leader and db.info.watch(listener) report leadership.
./drizzle exports drizzle() and migrate(). A database from sqlite.open() runs under Drizzle's own better-sqlite3 session through a small client object; a worker client runs under sqlite-proxy with a batch callback and client-queued transactions. Tests cover memory, fs, the client in Node and Chromium on OPFS.
…b stays open
The host takes a Web Lock (`hold` call) for its worker's whole life and the
leader tab waits on it, so the grant means the worker ended, however it
ended. An uncaught error in the worker is the second signal: the leader
terminates it and treats it the same way.
The leader then hands over as if its tab had closed: it drops what it had
queued, rejects its own started writes with SQLITE_BUSY ("the leader
changed"), releases the leader lock and joins again as a follower under a
new tab id. Followers and the tab itself resend reads and unstarted calls
to the next leader, as after any handover; if no other tab is waiting, the
same tab leads again with a new worker. A worker that ends before the
database is open fails the open with SQLITE_CANTOPEN.
The fake tabs get worker-scoped lock clients released on terminate and
error events. Drizzle's shared scenarios also run on a follower tab of a
shared connection.
dist/ is now one tsup build with code splitting for all four entries, so the error class, the protocol, values, options, the wasm loader and the rest live in shared chunks: client.error is sqlite.error and instanceof works across entries. The CJS files stay hand-written require(esm) shims. With shared chunks the browser entries can't get node: stubs of their own, so the shared code no longer imports node: modules. Reading the wasm from disk, the node-fs driver and the "db" lock's process checks go through core/platform.mts, which the main entry fills in from node.mts (an explicit provide() call, since "sideEffects": false would let a bundler drop a side-effect-only import). The nodeless plugin is gone; the bundle test now walks each browser entry's chunk graph. Before: 22 src modules were bundled into more than one entry (error and codes into three), 109,127 bytes of JS. After: none, 65,884 bytes.
…ation from SQLite's source archive The published amalgamation ships a parser generated without SQLITE_ENABLE_UPDATE_DELETE_LIMIT, so the define alone left ORDER BY / LIMIT on UPDATE and DELETE a syntax error. The build now pins sqlite-src-<n>.zip, runs SQLite's own makefile (make sqlite3.c with the option passed to lemon) using the host cc and the archive's bundled Jim Tcl, and compiles the result. Adds core tests and a Drizzle scenario for update/delete with orderBy and limit.
|
You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool. What Enabling Code Scanning Means:
For more information about GitHub Code Scanning, check out the documentation. |
… (CLDMV/.github v4.45.0)
Unnamed temporary files go in a per-process mkdtemp folder (0700) with mode 0600 and the folder is removed at exit. The "temp" lock root is now cldmv-sqlite-locks-<uid>, created 0700 and refused when it is a symlink, not a directory, owned by another user or writable by others; its locks are written 0700/0600. open() learns whether it created a file from an O_EXCL open instead of a separate existsSync check.
Shinrai
approved these changes
Nov 25, 2026
cldmv-bot Bot
added a commit
that referenced
this pull request
Nov 26, 2026
# `@cldmv/sqlite-wasm` v0.1.0 Changelog **Release Date**: November 2026 **Release Type**: Minor (first release) **Branch**: `release/0.1.0` --- ## Overview First release of `@cldmv/sqlite-wasm`: SQLite 3.54.1 compiled to WebAssembly, with one build and one API for Node.js and browsers. Databases are real files in Node, OPFS in a browser worker, or memory anywhere, and the files are standard SQLite files that native SQLite and `node:sqlite` open as usual. The wasm is built from SQLite's own source archive with wasi-sdk and binaryen. There is no Emscripten runtime and no fork of another wasm SQLite project. CI builds it from a pinned SQLite version and hash, and nothing binary is committed. --- ## ✨ Features ### Synchronous database API on one shared wasm instance ([#2](#2)) `sqlite.open(path, options)` returns a database with prepared statements, `run` / `get` / `all` / `iterate`, transactions (nested ones become savepoints), user-defined functions, aggregates, window functions and collations, plus `backup()`, `serialize()`, `attach()` and `checkpoint()`. Every connection in a process shares one module instance, which is what lets `ATTACH` and `backup()` work between them. Every SQLite failure is a `sqlite.error` carrying the result code name (`SQLITE_CONSTRAINT_PRIMARYKEY`) and the extended code number. ### Storage drivers: `fs`, `opfs` and `memory` ([#2](#2)) - **`fs`** (Node) writes real files through synchronous `fs` calls, with `fsync` on the file and on its folder after create and delete. - **`opfs`** (dedicated browser workers) uses OPFS sync access handles, opened before SQLite needs them, so no COOP/COEP headers are needed. - **`memory`** works anywhere. Each file name keeps its data for the life of the process. - **`auto`** (the default) picks `fs` in Node and `opfs` in a dedicated worker. WAL is the default journal mode, run in exclusive locking mode so the WAL index lives in heap memory. A clean `close()` checkpoints the WAL and removes the `-wal` file. `truncate` and `delete` rollback journals are available too. ### Locking between processes and tabs ([#2](#2)) In Node, opening a database takes an owner lock outside the file, and the `lock` option picks where it lives: `beside` (a `<db>.lock/` folder, the default), `temp` (a private per-user folder under `os.tmpdir()`), a folder you name, or `db` (a row inside the database). A lock whose process is gone is taken over. In browsers, the lock is a Web Lock per database. ### Browser main thread: worker host and client ([#2](#2)) `@cldmv/sqlite-wasm/host` runs the database in a worker with `host.listen(self)`, and `@cldmv/sqlite-wasm/worker` gives the main thread an async client with the same API, including nested transactions, `backup()` and `serialize()`. A `setup(db)` hook on the host runs on every open. ### Multi-tab sharing ([#2](#2)) With `share: true`, several tabs of one origin use one OPFS database. One tab's worker owns the database and the others send their requests to it over a `BroadcastChannel`. Ownership moves through a Web Lock when that tab closes or its worker ends, with reads retried against the new owner, and writes whose outcome is unknown failing with `SQLITE_BUSY` rather than running twice. `db.info.leader` and `db.info.watch()` show which tab owns it. ### Drizzle ORM driver ([#2](#2)) `@cldmv/sqlite-wasm/drizzle` exports `drizzle()` and `migrate()` for the synchronous database (Node or inside a worker) and for the async worker client on the main thread. `drizzle-orm` `^0.45.0` is an optional peer dependency. ### What is compiled in ([#2](#2)) FTS3/4/5, R\*Tree and Geopoly, JSON, `dbstat`, math and `percentile` functions, column metadata, STAT4, and `UPDATE`/`DELETE ... ORDER BY ... LIMIT` (generated into the parser from the source archive, so Drizzle's `.orderBy()` and `.limit()` work on updates and deletes). Foreign keys are on and double-quoted strings are identifiers only. The README's "What is compiled in" section has the full list, including what is left out. --- ## 🔧 CI & tooling - **Package layout and v4 CI** ([#1](#1)): tsup build into `dist/` with a CommonJS entry that re-exports the ESM one, `@cldmv/vitest-runner` tests, eslint and prettier, and the CLDMV v4 workflow set. - **The wasm build in CI** ([#2](#2)): pinned and hash-checked downloads of SQLite's source archive, wasi-sdk and binaryen, with retries and a cache. The browser tests run headless Chromium as their own CI job, and `npm run sqlite:bump` moves the SQLite pin. - **Generated types** ([#4](#4)): `types/` is built when the package is built or packed instead of being committed, and each published declaration's header names its own file. ## 🔧 Dependencies - `drizzle-orm` `^0.45.0`: optional peer dependency, needed only for `@cldmv/sqlite-wasm/drizzle`. - No runtime dependencies. --- ## Upgrade notes - First release, nothing to upgrade from. - Node.js `>=20.19.0` at runtime. The CommonJS entry needs `require(esm)`, so `^20.19.0` or `>=22.13.0`. - Browsers need a dedicated worker with OPFS sync access handles for persistent storage. Multi-tab sharing also needs Web Locks and `BroadcastChannel`. <details> <summary>👥 Contributors</summary> - @Shinrai </details> --- <!-- coverage-start -->  | Metric | Coverage | |--------|----------| | Statements | 100.0% | | Branches | 100.0% | | Functions | 100.0% | | Lines | 100.0% | *Avg: **100.0%** · `c0f05b9` · Node lts/** <!-- coverage-end --> <!-- co-authors --> Co-authored-by: Shinrai <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🚀 What's Changed
💥 Breaking Changes
No breaking changes
✨ Features
🐛 Bug Fixes
📦 Dependencies
No dependency updates
🔧 Other Changes
👥 Contributors