# PRAGMA 语句

> Turso 中的数据库配置与元数据命令
> Canonical HTML: https://tursodb.cn/zh-cn/docs/sql-reference/pragmas/
> Upstream Source (MIT): https://docs.turso.tech/sql-reference/pragmas
> Language: zh-CN

---
# PRAGMA 语句

PRAGMA 语句是用于查询或修改数据库配置、获取元数据以及控制数据库行为的特殊命令。与标准 SQL 不同，PRAGMA 是 SQLite 和 Turso 特有的。

## 语法

```sql
PRAGMA pragma-name;
PRAGMA pragma-name = value;
PRAGMA pragma-name(value);
```

## 数据库元数据

### database\_list

为每个已附加的数据库返回一行。

```sql
PRAGMA database_list;
-- seq | name | file
-- 0   | main | /path/to/database.db
```

### page\_count

返回数据库文件中的总页数。

```sql
PRAGMA page_count;
-- 42
```

### page\_size

返回或设置数据库的页大小。页大小只能在创建任何表之前设置。

```sql
PRAGMA page_size;
-- 4096

PRAGMA page_size = 8192;
```

### max\_page\_count

返回或设置数据库文件允许的最大页数。

```sql
PRAGMA max_page_count;
PRAGMA max_page_count = 1000000;
```

### freelist\_count

返回数据库文件中未使用页的数量。

```sql
PRAGMA freelist_count;
```

### encoding

返回数据库使用的文本编码。

```sql
PRAGMA encoding;
-- UTF-8
```

### schema\_version

返回 schema 版本号。每当 schema 发生变化时，该值都会递增。

```sql
PRAGMA schema_version;
-- 5
```

### application\_id

返回或设置存储在数据库头中的 application ID。应用程序可以使用这个 32 位整数来标识数据库文件格式。

```sql
PRAGMA application_id;
PRAGMA application_id = 12345;
```

### user\_version

返回或设置用户版本号。这是一个可供应用程序使用的 32 位整数。

```sql
PRAGMA user_version;
PRAGMA user_version = 3;
```

## Schema 内省

### table\_info

为指定表中的每一列返回一行。

```sql
PRAGMA table_info(table-name);
```

| 列 | 类型 | 描述 |
| - | - | - |
| cid | INTEGER | 列索引（从 0 开始） |
| name | TEXT | 列名 |
| type | TEXT | 声明的类型名 |
| notnull | INTEGER | 若存在 NOT NULL 约束则为 1 |
| dflt\_value | TEXT | 默认值表达式，或 NULL |
| pk | INTEGER | 若该列属于 PRIMARY KEY 则为 1 |

```sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
PRAGMA table_info(users);
-- cid | name  | type    | notnull | dflt_value | pk
-- 0   | id    | INTEGER | 0       |            | 1
-- 1   | name  | TEXT    | 1       |            | 0
-- 2   | email | TEXT    | 0       |            | 0
```

### table\_xinfo

与 `table_info` 类似，但还会包含隐藏列以及其他附加元数据。

```sql
PRAGMA table_xinfo(table-name);
```

返回的列与 `table_info` 相同，另外多出一个 `hidden` 列（普通列为 0，虚拟表中的隐藏列为非零值）。

### table\_list

为数据库中的每个表和视图返回一行。

```sql
PRAGMA table_list;
-- schema | name    | type  | ncol | wr | strict
-- main   | users   | table | 3    | 0  | 0
-- main   | orders  | table | 4    | 0  | 0
```

### index\_list

为指定表上的每个索引返回一行。

```sql
PRAGMA index_list(table-name);
-- seq | name           | unique | origin | partial
-- 0   | idx_email      | 1      | c      | 0
```

| 列 | 类型 | 描述 |
| - | - | - |
| seq | INTEGER | 索引序号 |
| name | TEXT | 索引名 |
| unique | INTEGER | 若索引为 UNIQUE 则为 1 |
| origin | TEXT | `c` 表示 CREATE INDEX，`u` 表示 UNIQUE 约束，`pk` 表示 PRIMARY KEY |
| partial | INTEGER | 若为部分索引则为 1 |

### index\_info

为指定索引中的每一列返回一行。

```sql
PRAGMA index_info(index-name);
-- seqno | cid | name
-- 0     | 2   | email
```

### index\_xinfo

与 `index_info` 类似，但会包含附加列。

```sql
PRAGMA index_xinfo(index-name);
```

### function\_list

为每个可用的 SQL 函数返回一行。

```sql
PRAGMA function_list;
-- name | builtin | type | enc | narg | flags
```

### pragma\_list

返回所有受支持 PRAGMA 命令的列表。

```sql
PRAGMA pragma_list;
```

## 数据库配置

### journal\_mode

返回或设置 journal 模式。

```sql
PRAGMA journal_mode;
-- wal

PRAGMA journal_mode = wal;
```

Turso 支持 WAL（预写日志）模式。不支持回滚 journal 模式（DELETE、TRUNCATE、PERSIST、MEMORY）。

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：Turso 支持一种用于并发写入的实验性 MVCC journal 模式：

```sql
PRAGMA journal_mode = mvcc;
```

当 MVCC 模式启用时，你可以使用 `BEGIN CONCURRENT` 进行乐观并发写事务。详情请参阅[事务](/zh-cn/docs/sql-reference/statements/transactions/#begin-concurrent)。

</div></div>


### cache\_size

返回或设置内存中保留的数据库页的建议最大数量。

```sql
PRAGMA cache_size;
PRAGMA cache_size = 2000;          -- 正数：页数
PRAGMA cache_size = -2000;         -- 负数：内存千字节数
```

### cache\_spill

启用或禁用缓存溢出（在缓存写满之前将脏页写入 WAL）。

```sql
PRAGMA cache_spill;
PRAGMA cache_spill = 0;    -- 禁用
PRAGMA cache_spill = 1;    -- 启用
```

### synchronous

控制用于持久性保证的 fsync 行为。

```sql
PRAGMA synchronous;
PRAGMA synchronous = OFF;    -- 不执行 fsync（最快，崩溃时存在损坏风险）
PRAGMA synchronous = FULL;   -- 每个事务后执行 fsync（最安全）
```

Turso 仅支持 `OFF` 和 `FULL`。

### temp\_store

控制临时表和索引的存储位置。

```sql
PRAGMA temp_store;
PRAGMA temp_store = 0;    -- DEFAULT
PRAGMA temp_store = 1;    -- FILE
PRAGMA temp_store = 2;    -- MEMORY
```

### busy\_timeout

设置忙等待超时时间（毫秒）。当表被锁定时，Turso 最多等待这么多毫秒，然后返回 SQLITE\_BUSY。

```sql
PRAGMA busy_timeout;
PRAGMA busy_timeout = 5000;   -- 5 秒
```

### query\_only

启用后，阻止对数据库的任何更改。

```sql
PRAGMA query_only = 1;    -- 启用只读模式
PRAGMA query_only = 0;    -- 禁用只读模式
```

### foreign\_keys

启用或禁用外键约束的执行。

```sql
PRAGMA foreign_keys;
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys = OFF;
```

为兼容 SQLite，外键约束执行默认处于关闭状态。

### legacy\_file\_format

返回旧式文件格式标志。

```sql
PRAGMA legacy_file_format;
```

### ignore\_check\_constraints

启用后，不执行 CHECK 约束。

```sql
PRAGMA ignore_check_constraints = 1;   -- 禁用 CHECK 约束
PRAGMA ignore_check_constraints = 0;   -- 启用 CHECK 约束
```

### data\_sync\_retry

控制 Turso 在磁盘同步（fsync）失败后是重试，还是将其视为致命错误。

```sql
PRAGMA data_sync_retry = 1;   -- 同步失败时重试
PRAGMA data_sync_retry = 0;   -- 不重试（默认）
```

### require\_where

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：一个在 SQLite 中没有对应项的安全类 pragma。

</div></div>


启用后，Turso 会拒绝任何不包含 `WHERE` 子句的 `UPDATE` 或 `DELETE`，以防止意外的全表修改。`i_am_a_dummy` 是一个启用相同行为的别名。

```sql
PRAGMA require_where = 1;
DELETE FROM users;            -- 被拒绝：没有 WHERE 子句
DELETE FROM users WHERE id = 1;  -- 允许

PRAGMA i_am_a_dummy = 1;      -- 等价于 require_where = 1
```

## 完整性检查

### integrity\_check

对整个数据库执行彻底的完整性检查。

```sql
PRAGMA integrity_check;
-- ok

PRAGMA integrity_check(N);    -- 仅检查前 N 个错误
```

如果未发现问题则返回 `ok`，否则每个错误返回一行。

### quick\_check

执行比 `integrity_check` 更快但不够彻底的完整性检查。

```sql
PRAGMA quick_check;
```

## WAL 操作

### wal\_checkpoint

强制执行一次 WAL checkpoint。

```sql
PRAGMA wal_checkpoint;
```

checkpoint 会将 WAL 文件中的页写回数据库文件。

## MVCC 调优

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：这些 pragma 仅在启用 MVCC 模式（`PRAGMA journal_mode = mvcc`）时生效。

</div></div>


### mvcc\_checkpoint\_threshold

设置 Turso 触发 MVCC checkpoint 之前所累积的已提交工作量。

```sql
PRAGMA mvcc_checkpoint_threshold = 1000;
```

### mvcc\_gc\_threshold

设置一个阈值，用于控制 Turso 对过期的 MVCC 行版本进行垃圾回收的积极程度。

```sql
PRAGMA mvcc_gc_threshold = 1000;
```

## 变更数据捕获

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：变更数据捕获（Change Data Capture，CDC）是 Turso 特有的功能，用于跟踪所有数据变更，以支持复制、审计和响应式应用。

</div></div>


### capture\_data\_changes\_conn

为当前连接启用 CDC。变更会被捕获到指定的表中。

```sql
PRAGMA capture_data_changes_conn('mode');
PRAGMA capture_data_changes_conn('mode,table_name');
```

出于向后兼容的考虑，旧名称 `unstable_capture_data_changes_conn` 仍然被接受。

| 参数 | 描述 |
| - | - |
| mode | 捕获模式：`off`、`id`、`before`、`after`、`full` |
| table\_name | 用于存储变更的自定义表名（默认：`turso_cdc`） |

#### 捕获模式

| 模式 | 描述 |
| - | - |
| `off` | 为此连接禁用 CDC |
| `id` | 仅捕获被修改行的主键/rowid |
| `before` | 捕获变更前的行状态（用于更新/删除） |
| `after` | 捕获变更后的行状态（用于插入/更新） |
| `full` | 同时捕获变更前和变更后的状态，以及更新详情 |

#### CDC 表结构

CDC 表包含以下列：

| 列 | 类型 | 描述 |
| - | - | - |
| change\_id | INTEGER | 自增的唯一标识符 |
| change\_time | INTEGER | Unix 纪元时间戳 |
| change\_type | INTEGER | 1（INSERT）、0（UPDATE）、-1（DELETE） |
| table\_name | TEXT | 被修改表的名称 |
| id | 不定 | 被修改行的主键/rowid |
| before | BLOB | 变更前的行数据（模式：before、full） |
| after | BLOB | 变更后的行数据（模式：after、full） |
| updates | BLOB | 被更新列的详情（模式：full） |

#### CDC 示例

```sql
-- Enable full CDC
PRAGMA capture_data_changes_conn('full');

-- Make changes
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users VALUES (1, 'Alice');
UPDATE users SET name = 'Alicia' WHERE id = 1;
DELETE FROM users WHERE id = 1;

-- Query the changes
SELECT change_type, table_name, id FROM turso_cdc;
-- 1  | users | 1    (INSERT)
-- 0  | users | 1    (UPDATE)
-- -1 | users | 1    (DELETE)

-- Use a custom table name
PRAGMA capture_data_changes_conn('full,audit_log');

-- Disable CDC
PRAGMA capture_data_changes_conn('off');
```

CDC 遵循事务边界。只有在事务提交时才会记录变更。如果事务回滚，则不会创建任何 CDC 条目。

## 加密

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：静态加密是 Turso 特有的功能。此功能为实验性功能，使用前必须[先启用](/zh-cn/docs/sql-reference/experimental-features/)。

</div></div>


### cipher

设置数据库的加密算法。

```sql
PRAGMA cipher = 'aegis256';
```

支持的加密算法：

| 加密算法 | 密钥大小 | 描述 |
| - | - | - |
| `aes128gcm` | 16 字节 | Galois/Counter 模式下的 AES-128 |
| `aes256gcm` | 32 字节 | Galois/Counter 模式下的 AES-256 |
| `aegis128l` | 16 字节 | AEGIS-128L |
| `aegis256` | 32 字节 | AEGIS-256（推荐） |
| `aegis128x2` | 16 字节 | 2 倍并行化的 AEGIS-128 |
| `aegis128x4` | 16 字节 | 4 倍并行化的 AEGIS-128 |
| `aegis256x2` | 32 字节 | 2 倍并行化的 AEGIS-256 |
| `aegis256x4` | 32 字节 | 4 倍并行化的 AEGIS-256 |

### hexkey

以十六进制字符串形式设置加密密钥。

```sql
PRAGMA hexkey = '2d7a30108d3eb3e45c90a732041fe54778bdcf707c76749fab7da335d1b39c1d';
```

#### 加密示例

```sql
-- Set cipher and key before creating tables
PRAGMA cipher = 'aegis256';
PRAGMA hexkey = '2d7a30108d3eb3e45c90a732041fe54778bdcf707c76749fab7da335d1b39c1d';

CREATE TABLE secrets (id INTEGER PRIMARY KEY, data TEXT);
INSERT INTO secrets VALUES (1, 'sensitive data');
```

或者，在数据库 URI 中指定加密参数：

```
file:database.db?cipher=aegis256&hexkey=2d7a30...
```

要打开一个已有的加密数据库，必须以 URI 参数的形式提供加密算法和密钥。

## 自定义类型

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">NOTE</div><div class="doc-callout-body">

**Turso 扩展**：自定义类型是 Turso 特有的功能。

</div></div>


### list\_types

列出所有可用类型（内置类型与自定义类型）及其元数据。

```sql
PRAGMA list_types;
-- type    | parent | encode | decode | default | operators
-- INTEGER |        |        |        |         |
-- REAL    |        |        |        |         |
-- TEXT    |        |        |        |         |
-- BLOB    |        |        |        |         |
-- ANY     |        |        |        |         |
```

关于创建自定义类型，请参阅 [CREATE TYPE](/zh-cn/docs/sql-reference/statements/create-type/)。

## 另请参阅

* [Transactions](/zh-cn/docs/sql-reference/statements/transactions/) —— 事务控制
* [CREATE TYPE](/zh-cn/docs/sql-reference/statements/create-type/) —— 自定义类型定义
* [Compatibility](/zh-cn/docs/sql-reference/compatibility/) —— 受支持 PRAGMA 的完整列表
