> ## Documentation Index
> Fetch the complete documentation index at: https://docs.2024921.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# KV → D1 迁移

> 从 KV 存储迁移到 D1 数据库

## 背景

Qingyu'Blog 最初使用 Cloudflare KV 作为存储后端，后来迁移到 D1（SQLite）：

| 特性  | KV        | D1        |
| --- | --------- | --------- |
| 一致性 | 最终一致性     | 强一致性      |
| 查询  | Key-Value | SQL       |
| 性能  | 较慢        | 边缘 SQLite |

## 迁移方式

### 本地执行

```bash theme={null}
export CLOUDFLARE_ACCOUNT_ID="你的账户ID"
export CLOUDFLARE_API_TOKEN="你的API Token"
export BLOG_KV_ID="KV命名空间ID"
export BLOG_D1_ID="D1数据库ID"
```

#### 预览（推荐先执行）

```bash theme={null}
node scripts/migrate-kv-to-d1.mjs --dry-run
```

仅输出 SQL，不实际写入。

#### 正式迁移

```bash theme={null}
node scripts/migrate-kv-to-d1.mjs
```

### GitHub Actions

1. **Actions** 标签页 → **Migrate KV to D1**
2. **Run workflow** → 选择 `migrate` 模式

## 迁移内容

| KV Key           | D1 表             | 说明    |
| ---------------- | ---------------- | ----- |
| `posts`          | `posts`          | 文章    |
| `comments:{id}`  | `comments`       | 评论    |
| `stats:{id}`     | `stats`          | 统计    |
| `admin:auth`     | `admin_auth`     | 管理员密码 |
| `admin:sessions` | `admin_sessions` | 会话    |
| `settings:*`     | `site_settings`  | 设置    |

<Warning>
  迁移前请备份 KV 数据。迁移过程不可逆。
</Warning>

## 验证

```bash theme={null}
# 检查文章数量
npx wrangler d1 execute blog --remote --command "SELECT COUNT(*) FROM posts"

# 检查评论数量
npx wrangler d1 execute blog --remote --command "SELECT COUNT(*) FROM comments"
```
