SQL Storage Adapter
Cross-platform SQL access for Node.js, web, and native runtimes with automatic adapter selection and consistent APIs.
The SQL Storage Adapter provides a single, ergonomic interface over SQLite (native and WASM), PostgreSQL, Capacitor, IndexedDB, and in-memory stores. It handles adapter discovery, capability detection, and advanced features like cloud backups so you can focus on your application logic.
🆕 NEW in v0.6.0: SQL Dialect abstractions for SQLite/Postgres parity + Cross-platform BLOB codec + Full-text search interface!
Features
- Auto-detected adapters –
createDatabase() inspects environment signals and picks the best backend (native SQLite, PostgreSQL, Capacitor, sql.js, IndexedDB, memory, etc.).
- Capability-aware API – consistent CRUD, transactions, batching, and event hooks across adapters with runtime capability introspection.
- 🆕 IndexedDB – sql.js + IndexedDB persistence wrapper for browser-native, offline-first web apps (uses sql.js for SQL execution, IndexedDB for storage).
- 🆕 Electron Adapter – Full IPC bridge with main/renderer process split, WAL management, auto-migrations, multi-window support.
- 🆕 Cross-Platform Sync – Real-time delta sync with vector clocks, WebSocket/HTTP transports, conflict resolution UI hooks, and device registry.
- 🆕 Performance Tiers – Configurable
fast, balanced, accurate, efficient presets for cost/accuracy tradeoffs. See Optimization Guide.
- 🆕 Lifecycle Hooks – Extensible hooks (
onBeforeQuery, onAfterQuery, onBeforeWrite, onAfterWrite) for logging, analytics, caching, and custom extensions.
- Cloud backups & migrations – built-in backup manager with compression, retention policies, and restore helpers plus migration utilities.
- Portable packaging – optional native dependencies; falls back to pure TypeScript/WASM adapters when native modules are unavailable.
- Browser-friendly –
./browser imports no Node built-in and no pg, and the browser field of package.json maps async_hooks, which the better-sqlite3 adapter loads only when it opens on Node, to an empty module in a page that bundles the root entry.
- Mobile/Offline Parity – Same APIs work across desktop, mobile (Capacitor), and browser with automatic sync support.
- 🆕 SQL Dialect – Write cross-platform SQL with
SqlDialect interface. Automatically translates INSERT OR IGNORE, json_extract, ifnull, PRAGMA between SQLite and PostgreSQL.
- 🆕 Full-Text Search –
IFullTextSearch interface abstracts FTS5 (SQLite) and tsvector/GIN (PostgreSQL) with unified createIndex, matchClause, rankExpression, and rebuildCommand APIs.
- 🆕 BLOB Codec –
IBlobCodec for cross-platform binary vector storage. NodeBlobCodec (Buffer) for server, BrowserBlobCodec (DataView) for web.
- 🆕 Database Export –
IDatabaseExporter with SqliteFileExporter (VACUUM INTO) and PostgresExporter (pg_dump).
- CI-first design – Vitest coverage, Codecov integration, and GitHub Actions workflows for linting, testing, releasing, and npm publish/tag automation.
Installation
# Core package: brings pg (PostgreSQL) and sql.js (WASM SQLite, and IndexedDB)
npm install @framers/sql-storage-adapter
# Install only the other engines you plan to use
npm install better-sqlite3 # Native SQLite for Node/Electron
npm install @capacitor-community/sqlite # Capacitor / mobile
pg and sql.js are dependencies of the package, listed once each, so they install with it, and @types/sql.js with them, so the declarations' sql.js import has types in a project that checks the declarations it reads (no skipLibCheck). better-sqlite3, @capacitor-community/sqlite, electron and @aws-sdk/client-s3 are optional peers: install the ones you use.
Windows users: ensure the Visual Studio Build Tools (C++ workload) are installed before adding better-sqlite3. On Linux, install python3, build-essential, and libssl-dev prior to npm install.
Note: If better-sqlite3 cannot be required, install native build tools before npm install, ensure your Node version matches available prebuilt binaries, or fall back to sql.js or indexeddb by setting STORAGE_ADAPTER=sqljs or STORAGE_ADAPTER=indexeddb.
better-sqlite3 13 needs Node-API 10: Node.js 22.14+ or 23.6+, or Electron 35+ (whose Node is 22.14). On an older runtime (Node.js 20, Node.js 22.13 and earlier, Electron 34 and earlier) install better-sqlite3@12; with 13 installed there, the adapter refuses to open, so the resolver falls back to sql.js, rather than letting the native binding crash the process. better-sqlite3 13 ships prebuilt binaries, but npm can still run node-gyp rebuild for it, which needs the build tools above (Python, and make and a C++ compiler, or the Visual Studio Build Tools on Windows): always when it installs from a lockfile (npm ci, or npm install with a package-lock.json), and on some platforms on a fresh install too (WiseLibs/better-sqlite3#1516).
Entries
The root entry exports everything and imports every adapter. A server takes its adapter from that adapter's own entry, with the rest from ./core, so its bundle carries neither sql.js nor the S3 client:
import { createPostgresAdapter } from '@framers/sql-storage-adapter/postgres';
import { createStorageFeatures, runSchemaMigrations, isUniqueViolation } from '@framers/sql-storage-adapter/core';
| Entry |
Holds |
@framers/sql-storage-adapter |
Everything, with createDatabase and the resolver |
./core |
Contracts and errors, dialects, full-text search, codecs, exporters, createStorageFeatures, the schema-migration runner, isUniqueViolation, the logger. No adapter |
./postgres, ./better-sqlite3, ./sqljs, ./indexeddb, ./capacitor |
One adapter each |
SupabaseAdapter (root) |
Deprecated: use ./postgres with the Supabase connection string |
./backup |
S3-compatible backups (@aws-sdk/client-s3) |
./authjs |
The Auth.js database adapter (also in ./core) |
./electron, ./electron/renderer, ./electron/preload |
The Electron adapters. ./electron/renderer holds only what a window uses; require('./electron/preload') gives one bundled CommonJS file for a sandboxed preload |
./sync, ./kv, ./types |
Cross-platform sync and the mutation sync, the key-value store, the types |
./browser |
What a page needs, in one entry: the IndexedDB adapter, the key-value module with its migration, the tab lock, and the mutation sync's client with its wire contract, transport, loop and change channel. Its modules import no Node built-in and no pg: the one package they import is sql.js |
Every entry has an import and a require condition. The CommonJS build under dist/cjs is made from the ES module build file by file, so a class has one identity whichever entry a caller takes it from. It carries its own declarations, so a CommonJS TypeScript consumer under node16 resolution type-checks against them. CI packs the package, installs it in a new project and checks each of these: require() of every entry, what each server entry and ./browser bundle, the preload, and that the CommonJS build repeats the browser field.
Quick Start
import { createDatabase } from '@framers/sql-storage-adapter';
async function main() {
// Automatically selects the best adapter for the current runtime
const db = await createDatabase();
await db.exec(`
CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY,
task TEXT NOT NULL,
done INTEGER DEFAULT 0
)
`);
await db.run('INSERT INTO todos (task) VALUES (?)', ['Ship cross-platform builds']);
const items = await db.all<{ id: number; task: string; done: number }>('SELECT * FROM todos');
console.log(items);
await db.close();
}
main().catch((error) => {
console.error('Database bootstrap failed', error);
process.exit(1);
});
Platform-Specific Examples
import { createDatabase, IndexedDbAdapter } from '@framers/sql-storage-adapter';
// Web (Browser): Uses IndexedDB
const webDb = await createDatabase({ priority: ['indexeddb', 'sqljs'] });
// Desktop (Electron): Uses better-sqlite3
const desktopDb = await createDatabase({ priority: ['better-sqlite3', 'sqljs'] });
// Mobile (Capacitor): Uses native SQLite
const mobileDb = await createDatabase({ priority: ['capacitor', 'indexeddb'] });
// Cloud (Node): Uses PostgreSQL. strict fails when DATABASE_URL is unset,
// where it would otherwise open a local SQLite file.
const cloudDb = await createDatabase({
url: process.env.DATABASE_URL,
strict: true
});
See Platform Strategy Guide for detailed pros/cons and architecture.
Adapter Matrix
| Adapter |
Package |
Ideal for |
Pros |
Considerations |