SQLite
Introduction
For local development purposes it’s nice to have a database ready to go with a few lines of code. That’s what the SQLite extension is for.
Installation
Install the SQLite extension like this:
npm install @hocuspocus/extension-sqlite better-sqlite3
npm install -D @types/better-sqlite3Since v4, the extension uses better-sqlite3 instead of the unmaintained sqlite3 package. If you're upgrading from v3, uninstall the old dependency with npm uninstall sqlite3. Existing SQLite database files are fully compatible — no data migration needed.
Configuration
database
Valid values are filenames, ":memory:" for an anonymous in-memory database and an empty string for an anonymous disk-based database. Anonymous databases are not persisted and when closing the database handle, their contents are lost.
https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback
Default: :memory:
schema
The SQLite schema that’s created for you.
Default:
CREATE TABLE IF NOT EXISTS "documents" (
"name" varchar(255) NOT NULL,
"data" blob NOT NULL,
UNIQUE(name)
)If you wrote a custom schema under v3, note that v4's better-sqlite3 uses named parameters without the $ prefix — rename $name to name and $data to data in your queries.
fetch
An async function to retrieve data from SQLite. If you change the schema, you probably want to override the query.
store
An async function to store data in SQLite. If you change the schema, you probably want to override the query.
Usage
By default, data is just “stored” in :memory:, so it’s wiped when you stop the server. You can pass a file name to
persist data on the disk.
import { Server } from "@hocuspocus/server";
import { SQLite } from "@hocuspocus/extension-sqlite";
const server = new Server({
extensions: [
new SQLite({
database: "db.sqlite",
}),
],
});
server.listen();Troubleshooting
Could not locate the bindings file
better-sqlite3 ships prebuilt native bindings, but they don't always match fresh Node.js versions on day one. If the server throws Error: Could not locate the bindings file on start-up, rebuild the binding from source in your server project:
npm rebuild better-sqlite3 --build-from-sourceThis compiles the native addon for your exact Node.js + OS + architecture combo. Requires a working C++ toolchain (Xcode Command Line Tools on macOS, build-essential on Debian/Ubuntu, or the Visual Studio Build Tools on Windows).