---
title: "SQLite"
canonical_url: "https://tiptap.zhcndoc.com/hocuspocus/server/extensions/sqlite"
---

# SQLite

## 介绍

对于本地开发来说，能够用几行代码快速准备好一个数据库非常方便。这就是 SQLite 扩展的作用。

## 安装

像这样安装 SQLite 扩展：

```bash
npm install @hocuspocus/extension-sqlite better-sqlite3
npm install -D @types/better-sqlite3
```

自 v4 起，该扩展使用 [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3) 代替不再维护的 `sqlite3` 包。如果您是从 v3 升级，请使用 `npm uninstall sqlite3` 卸载旧依赖。现有的 SQLite 数据库文件完全兼容——无需进行数据迁移。

## 配置

**database**

有效值可以是文件名，`:memory:` 代表匿名的内存数据库，空字符串代表匿名的基于磁盘的数据库。匿名数据库不会被持久化，当关闭数据库句柄时，其内容会丢失。

[https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback](https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback)

默认值: `:memory:`

**schema**

为您创建的 SQLite 模式。

默认:

```sql
CREATE TABLE IF NOT EXISTS "documents" (
  "name" varchar(255) NOT NULL,
  "data" blob NOT NULL,
  UNIQUE(name)
)
```

如果您在 v3 下编写了**自定义模式**，请注意 v4 的 `better-sqlite3` 使用不带 `$` 前缀的命名参数——请在您的查询中将 `$name` 重命名为 `name`，将 `$data` 重命名为 `data`。

**fetch**

一个用于从 SQLite 中检索数据的异步函数。如果您更改了模式，可能需要重写该查询。

**store**

一个用于将数据存储到 SQLite 的异步函数。如果您更改了模式，可能需要重写该查询。

**用法**

默认情况下，数据只是存储在 `:memory:` 中，因此当您停止服务器时数据会被清除。您可以传递文件名来将数据持久化到磁盘上。

```js
import { Server } from "@hocuspocus/server";
import { SQLite } from "@hocuspocus/extension-sqlite";

const server = new Server({
  extensions: [
    new SQLite({
      database: "db.sqlite",
    }),
  ],
});

server.listen();
```

## 故障排查

### `Could not locate the bindings file`

`better-sqlite3` 附带预编译的原生绑定，但它们并不总是在发布当天就与最新的 Node.js 版本匹配。如果服务器在启动时抛出 `Error: Could not locate the bindings file`，请在您的服务器项目中从源代码重新构建该绑定：

```bash
npm rebuild better-sqlite3 --build-from-source
```

这会为您精确的 Node.js + 操作系统 + 架构组合编译原生 addon。需要可用的 C++ 工具链（macOS 上的 Xcode Command Line Tools、Debian/Ubuntu 上的 `build-essential`，或 Windows 上的 Visual Studio Build Tools）。
