# Vercel

> 在 Vercel 的無伺服器與邊緣函式中使用 Turso。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/integrations/vercel/
> Upstream Source (MIT): https://docs.turso.tech/integrations/vercel
> Language: zh-TW

---
Turso 提供兩種從 Vercel 無伺服器與邊緣函式存取資料庫的方式：

* **透過 HTTP 的 SQL** — 每個查詢都會透過網路傳送到資料庫。設定簡單，且可在任何執行環境（包括邊緣函式）中運作，無需檔案系統存取。這就是你從其他所有資料庫所熟悉的模式。

* **函式內 SQLite（In-Function SQLite）** — 資料庫頁面會被複寫到無伺服器函式內。讀取在本機執行，沒有網路往返；寫入則直接送往遠端資料庫以確保持久性。如果你用過 Turso 的嵌入式副本，或用過 Cloudflare 搭配 SQLite 的 Durable Objects，這個模式會讓你感到熟悉。深入說明請參閱 [Bringing SQLite to Vercel Functions](https://turso.tech/blog/serverless)。

| | 透過 HTTP 的 SQL | 函式內 SQLite |
| - | - | - |
| **套件** | `@tursodatabase/serverless`、`@libsql/client` | `@tursodatabase/vercel-experimental` |
| **最適合** | 寫入密集的工作負載、沒有檔案系統的邊緣執行環境 | 讀取密集的工作負載、每租戶一個資料庫 |
| **讀取延遲** | 每個查詢一次網路往返 | 行程內 SQLite 讀取（零網路跳躍） |
| **寫入延遲** | 網路往返 | 網路往返（相同） |
| **多租戶** | 共用資料庫 | 每租戶一個資料庫，並自動隨需佈建 |
| **執行環境需求** | 僅需 `fetch` API | 臨時檔案系統（`/tmp`） |
| **ORM 支援** | Drizzle、Prisma 及其他（`@libsql/client`） | 尚未支援 |

## 透過 HTTP 的 SQL

從 Vercel 無伺服器與邊緣環境連線到 Turso 資料庫。請在 Vercel 環境中設定下列變數：

* `TURSO_DATABASE_URL` — 你的 Turso 資料庫 URL
* `TURSO_AUTH_TOKEN` — 你的 Turso 驗證權杖

| | `@tursodatabase/serverless` | `@libsql/client` |
| - | - | - |
| **搭配使用** | [Turso](/zh-tw/docs/tursodb/quickstart/) 資料庫 | [libSQL](/zh-tw/docs/libsql/) 資料庫 |
| **相依性** | 僅使用 `fetch` — 零原生相依性 | 需要 Node.js 或 `/web` 子路徑 |
| **並發寫入** | 是 — 內建於 Turso 引擎 | 不支援 |
| **ORM 支援** | 尚未支援 | Drizzle、Prisma 及其他 |

請依資料庫引擎選擇對應的驅動程式：[Turso](/zh-tw/docs/tursodb/quickstart/) 資料庫請用 **`@tursodatabase/serverless`**，[libSQL](/zh-tw/docs/libsql/) 資料庫與 ORM 整合（Drizzle、Prisma）請用 **`@libsql/client`**。

### 快速開始

<div class="doc-tabs" data-doc-tabs>
<div class="doc-tab-list" role="tablist">
<button type="button" role="tab" class="doc-tab-btn is-active" aria-selected="true" data-tab-idx="0">@tursodatabase/serverless</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="1">@libsql/client</button>
</div>
<div class="doc-tab-panel is-active" role="tabpanel" data-tab-panel="0">

`@tursodatabase/serverless` 套件僅使用 `fetch` API 連線到 Turso — 沒有原生相依性，是邊緣與無伺服器執行環境中體積最小的選項。

```bash
npm install @tursodatabase/serverless
```

```typescript
import { connect } from "@tursodatabase/serverless";

const conn = connect({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

const stmt = await conn.prepare("SELECT * FROM users WHERE id = ?");
const row = await stmt.get([123]);
```

若需與 libSQL 用戶端 API 相容，請使用相容模組：

```typescript
import { createClient } from "@tursodatabase/serverless/compat";

const client = createClient({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="1" hidden>

`@libsql/client` 套件是在整個 Turso 生態系中使用的正式環境就緒 libSQL 驅動程式。在 Vercel 無伺服器與邊緣執行環境中請使用 `/web` 匯入：

```bash
npm install @libsql/client
```

```typescript
import { createClient } from "@libsql/client/web";

const client = createClient({
  url: process.env.TURSO_DATABASE_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN!,
});

const result = await client.execute({
  sql: "SELECT * FROM users WHERE id = ?",
  args: [123],
});
```

> [!NOTE]
>
> 在 Vercel 部署中請使用 `@libsql/client/web` 而非 `@libsql/client`。`/web` 匯入採用 HTTP 協定，可與邊緣及無伺服器執行環境相容。

</div>
</div>


## 函式內 SQLite

<div class="doc-callout doc-callout-warning"><div class="doc-callout-title">WARNING</div><div class="doc-callout-body">

`@tursodatabase/vercel-experimental` 套件目前為 beta。它可能仍含有錯誤與非預期行為。在正式資料上請謹慎使用，並確保你已有備份。

</div></div>


`@tursodatabase/vercel-experimental` 套件會將 SQLite 資料庫頁面複寫到無伺服器函式本身。讀取會針對本機副本執行，沒有網路往返。寫入則直接送往遠端資料庫，以確保持久性與一致性。這種方式非常適合讀取密集、且每查詢網路延遲為主要成本的工作負載。

* **每租戶隔離與分片** — 每個代理、工作區或工作階段都可以有自己的資料庫，並擁有獨立的儲存上限
* **運算與資料共置** — 業務邏輯與資料庫相鄰執行，可實現零跳躍讀取，且每個請求可執行大量查詢
* **自動隨需佈建** — 呼叫 `createDb()` 時即隱含建立資料庫，無需重新部署或管理繫結

如果你用過 Turso 的嵌入式副本，或用過 Cloudflare 搭配 SQLite 的 Durable Objects，這個模式會讓你感到熟悉。

### 快速開始

安裝套件：

```bash
npm install @tursodatabase/vercel-experimental
```

取得你的 Turso API 權杖與組織 slug：

```bash
turso auth api-tokens mint my-vercel-token
turso org list
```

在你的 Vercel 專案中新增環境變數：

```
TURSO_API_TOKEN=your-api-token
TURSO_ORG=your-org-slug
TURSO_GROUP=your-group-name
TURSO_DATABASE=your-database-name
```

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

`TURSO_GROUP` 環境變數會將所有資料庫存取限制在單一群組內。即使 API 權杖授予了整個組織的存取權，控制了資料庫名稱的攻擊者也只能存取所設定群組內的資料庫。若可行，仍建議將資料庫名稱存放為秘密環境變數。

</div></div>


使用 `createDb()` 開啟資料庫並開始查詢：

```ts
import { createDb } from "@tursodatabase/vercel-experimental";

const db = await createDb(process.env.TURSO_DATABASE!);
try {
  // Create tables
  await db.execute(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      email TEXT UNIQUE
    )
  `);

  // Insert data
  await db.execute(
    "INSERT INTO users (name, email) VALUES (?, ?)",
    ["Alice", "alice@example.com"]
  );

  // Query data
  const result = await db.query("SELECT * FROM users");
  console.log(result.rows);
} finally {
  await db.close(); // Syncs and closes the connection
}
```

### 每租戶資料庫

自動佈建讓實作每租戶一個資料庫的模式變得十分直接。不用讓所有租戶共用單一資料庫，而是讓每個使用者或工作階段擁有自己獨立的 SQLite 資料庫。只要從租戶識別碼推導出資料庫名稱即可：

```ts
// Per-user database
const db = await createDb(`user-${userId}`);

// Per-agent-session database
const db = await createDb(`session-${sessionId}`);
```

由於驅動程式會隨需建立資料庫，因此沒有佈建步驟、不需執行遷移，也不必設定連線路由。每個租戶的資料在 SQLite 層級完全隔離，且每個資料庫都能獨立享有部分同步（partial-sync）讀取的好處。

### API 參考

**`createDb(name, options?)`**

建立或取得資料庫執行個體。若資料庫不存在，會在所設定的群組（`TURSO_GROUP`）內自動建立。在單一次函式呼叫中，以相同名稱呼叫 `createDb()` 會傳回既有的執行個體。

```ts
const db = await createDb(process.env.TURSO_DATABASE!, {
  remoteWrites: false,     // Batch writes locally and push on close() (optional, default: true)
});
```

當 `remoteWrites` 為 `true`（預設值）時，寫入陳述式（`INSERT`、`UPDATE`、`DELETE`）會直接送往遠端 Turso 資料庫，以立即確保持久性。設為 `false` 時，寫入會套用到本機 SQLite 副本，並在呼叫 `db.push()` 或 `db.close()` 時以單一批次推送。這對於批次匯入或可接受最終可見性的背景任務很有用。

**`db.query(sql, params?)`**

執行 SELECT 查詢並傳回結果。

```ts
const result = await db.query("SELECT * FROM users WHERE id = ?", [1]);

console.log(result.columns); // ["id", "name", "email"]
console.log(result.rows);    // [[1, "Alice", "alice@example.com"]]
```

**`db.execute(sql, params?)`**

執行 INSERT、UPDATE、DELETE 或 DDL 陳述式。預設情況下，寫入會直接送往遠端 Turso 資料庫。若設定了 `remoteWrites: false`，寫入會套用到本機，並在 `close()` 時推送。

```ts
await db.execute("UPDATE users SET name = ? WHERE id = ?", ["Bob", 1]);
```

**`db.close()`**

關閉連線。若設定了 `remoteWrites: false`，這也會將任何待處理的本機寫入推送到遠端 Turso 資料庫。請務必在 `finally` 區塊中呼叫它。作為安全網，該套件會向 Vercel 的 [`waitUntil()`](https://vercel.com/docs/functions/functions-api-reference#waituntil) API 註冊一個回呼，若在函式完成後 5 秒內未呼叫 `close()`，便會推送待處理的變更。

```ts
const db = await createDb(process.env.TURSO_DATABASE!);
try {
  await db.execute("INSERT INTO users (name) VALUES (?)", ["Charlie"]);
} finally {
  await db.close();
}
```

**`db.push()`**

在不關閉連線的情況下，手動將本機變更推送到遠端 Turso 資料庫。僅在使用 `remoteWrites: false` 時適用。

```ts
await db.execute("INSERT INTO users (name) VALUES (?)", ["Charlie"]);
await db.push(); // Sync without closing
```

**`db.pull()`**

從遠端 Turso 資料庫拉取最新變更。

```ts
await db.pull();
```
