关于 cloudflare-hyperdrive
cloudflare-hyperdrive 是指导在 Cloudflare Workers 中连接现有 PostgreSQL 和 MySQL 数据库的技能,面向构建数据库驱动型 Worker 的开发者。内容涵盖连接池、查询缓存、驱动与 ORM 配置及安全实践。
主要功能
- 01配置 Hyperdrive 绑定
- 02连接池与查询缓存
- 03使用 PostgreSQL 和 MySQL 驱动
- 04集成 Drizzle 和 Prisma
- 05提供故障排查与部署参考
适用场景
- 01让 Worker 查询现有数据库
- 02在 Worker 中执行参数化查询
- 03在数据库操作中使用事务
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill cloudflare-hyperdrive安装后在 Claude Code 中输入/cloudflare-hyperdrive确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/connection-pooling.mddrizzle-integration.mdprisma-integration.mdquery-caching.mdsetup-guide.mdsupported-databases.mdtls-ssl-setup.mdtroubleshooting.mdwrangler-commands.mdscripts/check-versions.shtemplates/drizzle-mysql.tsdrizzle-postgres.tslocal-dev-setup.shmysql2-basic.tspostgres-basic.tspostgres-js.tspostgres-pool.tsprisma-postgres.tswrangler-hyperdrive-config.jsonc详细介绍
Cloudflare Hyperdrive
状态:已可用于生产环境 ✅ | 上次验证时间:2025-11-18
什么是 Hyperdrive?
将 Workers 连接到现有的 PostgreSQL/MySQL 数据库:
- 全局连接池
- 查询缓存
- 降低延迟
- 适用于 node-postgres、postgres.js、mysql2
快速入门(5 分钟)
1. 创建 Hyperdrive 配置
bunx wrangler hyperdrive create my-db \
--connection-string="postgres://user:pass@host:5432/database"
保存 id!
2. 配置绑定
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2024-09-23",
"compatibility_flags": ["nodejs_compat"], // REQUIRED!
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<ID_FROM_STEP_1>"
}
]
}
3. 安装驱动
bun add pg # or postgres, or mysql2
4. 查询数据库
import { Client } from 'pg';
export default {
async fetch(request, env, ctx) {
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT * FROM users LIMIT 10');
await client.end();
return Response.json(result.rows);
}
};
加载 references/setup-guide.md 查看完整操作流程。
重要规则
务必做到 ✅
- 启用 nodejs_compat 标志(必需!)
- 使用 env.HYPERDRIVE.connectionString(不要使用原始数据库连接字符串)
- 查询后关闭连接
- 明确处理错误
- 使用连接池(内置)
- 使用 wrangler dev 进行本地测试
- 监控查询性能
- 使用预处理语句
- 启用查询缓存(自动启用)
- 保护连接字符串(使用密钥)
切勿这样做 ❌
- 切勿跳过 nodejs_compat(驱动将无法运行)
- 切勿在 Workers 中使用原始数据库连接字符串
- 切勿让连接保持打开状态(连接池会耗尽)
- 切勿跳过错误处理(数据库可能会发生故障)
- 切勿在代码中硬编码凭据
- 切勿超出连接数限制
- 切勿使用 eval/Function(Workers 会阻止)
- 生产数据库切勿跳过 TLS
- 切勿使用阻塞式查询(Worker 会超时)
- 切勿向用户暴露数据库错误
数据库驱动
PostgreSQL(node-postgres)
import { Client } from 'pg';
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query('SELECT * FROM users');
await client.end();
PostgreSQL(postgres.js)
import postgres from 'postgres';
const sql = postgres(env.HYPERDRIVE.connectionString);
const users = await sql`SELECT * FROM users`;
MySQL
import mysql from 'mysql2/promise';
const connection = await mysql.createConnection(env.HYPERDRIVE.connectionString);
const [rows] = await connection.execute('SELECT * FROM users');
await connection.end();
与 Drizzle ORM 搭配使用
import { drizzle } from 'drizzle-orm/node-postgres';
import { Client } from 'pg';
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const db = drizzle(client);
const users = await db.select().from(usersTable);
await client.end();
常见用例
用例 1:只读查询
export default {
async fetch(request, env, ctx) {
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const users = await client.query('SELECT * FROM users WHERE active = true');
await client.end();
return Response.json(users.rows);
}
};
用例 2:参数化查询
const userId = new URL(request.url).searchParams.get('id');
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
const result = await client.query(
'SELECT * FROM users WHERE id = $1',
[userId]
);
await client.end();
用例 3:事务
const client = new Client({ connectionString: env.HYPERDRIVE.connectionString });
await client.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE accounts SET balance = balance - 100 WHERE id = $1', [1]);
await client.query('UPDATE accounts SET balance = balance + 100 WHERE id = $1', [2]);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
await client.end();
}
支持的数据库
PostgreSQL:
- Amazon RDS
- Amazon Aurora
- Neon
- Supabase
- Railway
- Render
- DigitalOcean
- 任意 PostgreSQL 11 及更高版本
MySQL:
- Amazon RDS
- Amazon Aurora
- PlanetScale
- 任意 MySQL 5.7 及更高版本
官方文档
- Hyperdrive 概览:https://developers.cloudflare.com/hyperdrive/
- 快速入门:https://developers.cloudflare.com/hyperdrive/get-started/
- 配置:https://developers.cloudflare.com/hyperdrive/configuration/
随附资源
参考文档(references/):
setup-guide.md- 完整的设置流程(创建配置、绑定、查询)connection-pooling.md- 连接池配置和最佳实践query-caching.md- 查询缓存策略和优化drizzle-integration.md- Drizzle ORM 集成模式prisma-integration.md- Prisma ORM 集成模式supported-databases.md- 支持的 PostgreSQL 和 MySQL 服务提供商完整列表tls-ssl-setup.md- 安全连接的 TLS/SSL 配置troubleshooting.md- 常见问题及解决方案wrangler-commands.md- Hyperdrive 的完整 wrangler CLI 命令
模板(templates/):
postgres-basic.ts- 使用 node-postgres 的基础 PostgreSQL 配置postgres-js.ts- 使用 postgres.js 驱动的 PostgreSQL 配置postgres-pool.ts- 使用连接池的 PostgreSQL 配置mysql2-basic.ts- 使用 mysql2 驱动的 MySQL 配置drizzle-postgres.ts- 使用 PostgreSQL 的 Drizzle ORM 配置drizzle-mysql.ts- 使用 MySQL 的 Drizzle ORM 配置prisma-postgres.ts- 使用 PostgreSQL 的 Prisma ORM 配置local-dev-setup.sh- 本地开发设置脚本wrangler-hyperdrive-config.jsonc- Wrangler 配置示例
有疑问?遇到问题?
- 查看
references/setup-guide.md了解完整设置流程 - 确认已启用 nodejs_compat 标志
- 确认使用 env.HYPERDRIVE.connectionString
- 检查连接是否已正确关闭
评论
支持 Markdown