# PRAGMA 陳述式

> Turso 中的資料庫設定與中繼資料命令
> Canonical HTML: https://tursodb.cn/zh-tw/docs/sql-reference/pragmas/
> Upstream Source (MIT): https://docs.turso.tech/sql-reference/pragmas
> Language: zh-TW

---
# 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

回傳結構描述版本號。每次結構描述變更時，此數值會遞增。

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

### application\_id

回傳或設定儲存在資料庫標頭中的應用程式 ID。應用程式可使用這個 32 位元整數來識別資料庫檔案格式。

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

### user\_version

回傳或設定使用者版本號。這是供應用程式使用的 32 位元整數。

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

## 結構描述內省

### 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

回傳或設定日誌模式。

```sql
PRAGMA journal_mode;
-- wal

PRAGMA journal_mode = wal;
```

Turso 支援 WAL（預寫日誌，Write-Ahead Logging）模式。不支援回滾日誌模式（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 日誌模式，可進行並發寫入：

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

啟用 MVCC 模式時，您可以使用 `BEGIN CONCURRENT` 進行樂觀的並發寫入事務。詳情請參閱 [Transactions](/zh-tw/docs/sql-reference/statements/transactions/#begin-concurrent)。

</div></div>


### cache\_size

回傳或設定保留在記憶體中的資料庫頁面建議上限數量。

```sql
PRAGMA cache_size;
PRAGMA cache_size = 2000;          -- positive: number of pages
PRAGMA cache_size = -2000;         -- negative: kilobytes of memory
```

### cache\_spill

啟用或停用快取溢出（在快取滿之前將髒頁面寫入 WAL）。

```sql
PRAGMA cache_spill;
PRAGMA cache_spill = 0;    -- disable
PRAGMA cache_spill = 1;    -- enable
```

### synchronous

控制 fsync 行為以提供持久性保證。

```sql
PRAGMA synchronous;
PRAGMA synchronous = OFF;    -- no fsync (fastest, risk of corruption on crash)
PRAGMA synchronous = FULL;   -- fsync after every transaction (safest)
```

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 seconds
```

### query\_only

啟用後，可防止對資料庫進行任何變更。

```sql
PRAGMA query_only = 1;    -- enable read-only mode
PRAGMA query_only = 0;    -- disable read-only mode
```

### 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;   -- disable CHECK constraints
PRAGMA ignore_check_constraints = 0;   -- enable CHECK constraints
```

### data\_sync\_retry

控制 Turso 在磁碟同步（fsync）失敗後是否重試，而非將其視為致命錯誤。

```sql
PRAGMA data_sync_retry = 1;   -- retry on sync failure
PRAGMA data_sync_retry = 0;   -- do not retry (default)
```

### 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;            -- rejected: no WHERE clause
DELETE FROM users WHERE id = 1;  -- allowed

PRAGMA i_am_a_dummy = 1;      -- equivalent to require_where = 1
```

## 完整性檢查

### integrity\_check

對整個資料庫執行完整徹底的完整性檢查。

```sql
PRAGMA integrity_check;
-- ok

PRAGMA integrity_check(N);    -- check only the first N errors
```

若未發現問題則回傳 `ok`，否則每個錯誤回傳一列。

### quick\_check

執行比 `integrity_check` 更快速但較不徹底的完整性檢查。

```sql
PRAGMA quick_check;
```

## WAL 操作

### wal\_checkpoint

強制執行 WAL 檢查點。

```sql
PRAGMA wal_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 檢查點之前所累積的已提交工作量。

```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-tw/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-tw/docs/sql-reference/statements/create-type/)。

## 另請參閱

* [Transactions](/zh-tw/docs/sql-reference/statements/transactions/) 以了解事務控制
* [CREATE TYPE](/zh-tw/docs/sql-reference/statements/create-type/) 以了解自訂型別定義
* [Compatibility](/zh-tw/docs/sql-reference/compatibility/) 以取得支援的 PRAGMA 完整清單
