hyperdrive
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHyperdrive
Hyperdrive
Accelerate access to existing PostgreSQL and MySQL databases with connection pooling and caching.
借助连接池与缓存功能,加速访问现有PostgreSQL和MySQL数据库。
FIRST: Create Hyperdrive Configuration
第一步:创建Hyperdrive配置
bash
undefinedbash
undefinedCreate a Hyperdrive configuration for your database
Create a Hyperdrive configuration for your database
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
npx wrangler hyperdrive create <YOUR_CONFIG_NAME> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"
Copy the ID from the output for your wrangler.jsonc
Copy the ID from the output for your wrangler.jsonc
Add the binding to `wrangler.jsonc`:
```jsonc
{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<YOUR_DATABASE_ID>"
}
]
}
将绑定添加至`wrangler.jsonc`中:
```jsonc
{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<YOUR_DATABASE_ID>"
}
]
}When to Use
使用场景
Use Hyperdrive when:
- Connecting to existing databases - PostgreSQL or MySQL hosted anywhere
- Reducing connection latency - Connection pooling eliminates per-request connection overhead
- Geographic distribution - Cache query results at the edge for read-heavy workloads
- Database migration - Connect Workers to traditional databases without rewriting apps
- Connection limits - Share connections across many Workers efficiently
在以下场景中使用Hyperdrive:
- 连接现有数据库 - 托管于任意位置的PostgreSQL或MySQL数据库
- 降低连接延迟 - 连接池消除了每个请求的连接开销
- 地理分布式部署 - 在边缘缓存查询结果,适用于读密集型工作负载
- 数据库迁移 - 在无需重写应用的前提下,将Workers连接至传统数据库
- 连接限制优化 - 在多个Workers之间高效共享连接
Quick Reference
快速参考
| Operation | API |
|---|---|
| Get connection string | |
| Connect with Postgres.js | |
| Query with Postgres.js | |
| No cleanup needed | Hyperdrive handles connection pooling—don't call |
| List configs | |
| Get config details | |
| Update config | |
| Delete config | |
| 操作 | API |
|---|---|
| 查询连接字符串 | |
| 使用Postgres.js连接 | |
| 使用Postgres.js执行查询 | |
| 无需手动清理 | Hyperdrive会处理连接池管理——请勿调用 |
| 列出所有配置 | |
| 获取配置详情 | |
| 更新配置 | |
| 删除配置 | |
Connect with Postgres.js
使用Postgres.js连接
Install dependencies first:
bash
npm install postgresCode:
typescript
import postgres from "postgres";
export interface Env {
// If you set another name in the Wrangler config file as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a database client that connects to your database via Hyperdrive.
//
// Hyperdrive generates a unique connection string you can pass to
// supported drivers, including node-postgres, Postgres.js, and the many
// ORMs and query builders that use these drivers.
const sql = postgres(env.HYPERDRIVE.connectionString);
try {
// Test query
const results = await sql`SELECT * FROM pg_tables`;
// Return result rows as JSON
return Response.json(results);
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;首先安装依赖:
bash
npm install postgres代码示例:
typescript
import postgres from "postgres";
export interface Env {
// If you set another name in the Wrangler config file as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a database client that connects to your database via Hyperdrive.
//
// Hyperdrive generates a unique connection string you can pass to
// supported drivers, including node-postgres, Postgres.js, and the many
// ORMs and query builders that use these drivers.
const sql = postgres(env.HYPERDRIVE.connectionString);
try {
// Test query
const results = await sql`SELECT * FROM pg_tables`;
// Return result rows as JSON
return Response.json(results);
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;Connection Management
连接管理
Important: Do NOT call or close connections manually.
sql.end()- Hyperdrive manages connection pooling automatically
- Connections are reused across requests efficiently
- Closing connections can cause errors and reduce performance
- The connection pool persists between Worker invocations
typescript
// ❌ DON'T DO THIS
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
await sql.end(); // DON'T close the connection
// ✅ DO THIS INSTEAD
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
// Let Hyperdrive manage the connection注意: 请勿调用或手动关闭连接。
sql.end()- Hyperdrive会自动管理连接池
- 连接会在多个请求之间高效复用
- 手动关闭连接可能会导致错误并降低性能
- 连接池会在Worker调用之间保持存在
typescript
// ❌ DON'T DO THIS
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
await sql.end(); // DON'T close the connection
// ✅ DO THIS INSTEAD
const sql = postgres(env.HYPERDRIVE.connectionString);
await sql`SELECT * FROM users`;
// Let Hyperdrive manage the connectionSupported Drivers
支持的驱动
| Driver | Package | Notes |
|---|---|---|
| Postgres.js | | Recommended - 3.4.5 or later |
| node-postgres | | Widely used, works well |
| Drizzle ORM | | Use with postgres driver |
| Prisma | | Add |
See references/drivers.md for detailed driver integration examples.
| 驱动 | 包名 | 说明 |
|---|---|---|
| Postgres.js | | 推荐使用 - 版本3.4.5及以上 |
| node-postgres | | 应用广泛,兼容性良好 |
| Drizzle ORM | | 需搭配postgres驱动使用 |
| Prisma | | 需在连接字符串中添加 |
如需查看详细的驱动集成示例,请参阅references/drivers.md。
ORM Integration
ORM集成
Drizzle ORM
Drizzle ORM
typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
export default {
async fetch(request, env, ctx): Promise<Response> {
const client = postgres(env.HYPERDRIVE.connectionString);
const db = drizzle(client);
const results = await db.select().from(users);
return Response.json(results);
}
};typescript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
export default {
async fetch(request, env, ctx): Promise<Response> {
const client = postgres(env.HYPERDRIVE.connectionString);
const db = drizzle(client);
const results = await db.select().from(users);
return Response.json(results);
}
};Prisma
Prisma
Important: Add to prevent connection pool exhaustion:
?connection_limit=1typescript
import { PrismaClient } from '@prisma/client';
export default {
async fetch(request, env, ctx): Promise<Response> {
// Append connection_limit=1 for Prisma
const prisma = new PrismaClient({
datasourceUrl: env.HYPERDRIVE.connectionString + '?connection_limit=1'
});
const users = await prisma.user.findMany();
return Response.json(users);
}
};注意: 需添加以避免连接池耗尽:
?connection_limit=1typescript
import { PrismaClient } from '@prisma/client';
export default {
async fetch(request, env, ctx): Promise<Response> {
// Append connection_limit=1 for Prisma
const prisma = new PrismaClient({
datasourceUrl: env.HYPERDRIVE.connectionString + '?connection_limit=1'
});
const users = await prisma.user.findMany();
return Response.json(users);
}
};MySQL Support
MySQL支持
Hyperdrive also supports MySQL databases:
bash
undefinedHyperdrive同样支持MySQL数据库:
bash
undefinedCreate MySQL Hyperdrive config
Create MySQL Hyperdrive config
npx wrangler hyperdrive create my-mysql
--connection-string="mysql://user:password@host:3306/database"
--connection-string="mysql://user:password@host:3306/database"
```typescript
import { connect } from '@planetscale/database';
export default {
async fetch(request, env, ctx): Promise<Response> {
const conn = connect({ url: env.HYPERDRIVE.connectionString });
const results = await conn.execute('SELECT * FROM users');
return Response.json(results.rows);
}
};npx wrangler hyperdrive create my-mysql
--connection-string="mysql://user:password@host:3306/database"
--connection-string="mysql://user:password@host:3306/database"
```typescript
import { connect } from '@planetscale/database';
export default {
async fetch(request, env, ctx): Promise<Response> {
const conn = connect({ url: env.HYPERDRIVE.connectionString });
const results = await conn.execute('SELECT * FROM users');
return Response.json(results.rows);
}
};Caching Configuration
缓存配置
Hyperdrive automatically caches query results. Configure caching behavior when creating the config:
bash
undefinedHyperdrive会自动缓存查询结果。可在创建配置时自定义缓存行为:
bash
undefinedDefault: cache enabled with 60s TTL
Default: cache enabled with 60s TTL
npx wrangler hyperdrive create my-db
--connection-string="postgres://..."
--caching-disabled=false
--max-age=60
--connection-string="postgres://..."
--caching-disabled=false
--max-age=60
**Caching behavior:**
- Only **read queries** (SELECT) are cached
- Write queries (INSERT, UPDATE, DELETE) are never cached
- Cache is automatically invalidated when writes occur to the same tablenpx wrangler hyperdrive create my-db
--connection-string="postgres://..."
--caching-disabled=false
--max-age=60
--connection-string="postgres://..."
--caching-disabled=false
--max-age=60
**缓存行为说明:**
- 仅**读查询**(SELECT语句)会被缓存
- 写查询(INSERT、UPDATE、DELETE语句)永远不会被缓存
- 当对同一张表执行写操作时,缓存会自动失效Detailed References
详细参考文档
- references/setup.md - Creating configs, connection strings, security
- references/drivers.md - Driver-specific patterns, ORMs, troubleshooting
- references/testing.md - Local PostgreSQL setup, Vitest integration, testing with real databases
- references/setup.md - 配置创建、连接字符串、安全设置相关内容
- references/drivers.md - 驱动特定模式、ORM集成、故障排查相关内容
- references/testing.md - 本地PostgreSQL搭建、Vitest集成、真实数据库测试相关内容
Best Practices
最佳实践
- Use Postgres.js 3.4.5+ - Best compatibility and performance with Hyperdrive
- Never call sql.end() - Hyperdrive manages connection lifecycle
- One config per database - Reuse the same Hyperdrive binding across Workers
- Use Prisma carefully - Always add to the connection string
?connection_limit=1 - Test locally with wrangler dev - Use flag to connect through Hyperdrive
--remote - Store credentials securely - Never commit connection strings; use environment variables
- Monitor with observability - Enable in to track query performance
wrangler.jsonc - Connection string format - Use standard Postgres/MySQL connection string format
- 使用Postgres.js 3.4.5及以上版本 - 与Hyperdrive的兼容性和性能最佳
- 请勿调用sql.end() - Hyperdrive会管理连接的生命周期
- 每个数据库对应一个配置 - 在多个Workers之间复用同一个Hyperdrive绑定
- 谨慎使用Prisma - 务必在连接字符串中添加
?connection_limit=1 - 使用wrangler dev进行本地测试 - 使用参数通过Hyperdrive连接
--remote - 安全存储凭证 - 请勿将连接字符串提交至版本控制系统,应使用环境变量
- 通过可观测性工具监控 - 在中启用该功能以追踪查询性能
wrangler.jsonc - 连接字符串格式规范 - 使用标准的Postgres/MySQL连接字符串格式
Troubleshooting
故障排查
Connection errors:
- Verify your database allows connections from Cloudflare IPs
- Check firewall rules and security groups
- Test connection string format (must be valid Postgres/MySQL URL)
Prisma connection pool errors:
- Add to the connection string
?connection_limit=1 - Ensure Prisma client is initialized once per request, not globally
"Too many connections" errors:
- Your origin database may have reached its connection limit
- Increase max connections on your database server
- Hyperdrive already pools connections efficiently
Local development:
bash
undefined连接错误:
- 确认你的数据库允许来自Cloudflare IP的连接
- 检查防火墙规则和安全组设置
- 测试连接字符串格式(必须是有效的Postgres/MySQL URL)
Prisma连接池错误:
- 在连接字符串中添加
?connection_limit=1 - 确保Prisma客户端是每个请求初始化一次,而非全局初始化
“连接数过多”错误:
- 你的源数据库可能已达到连接数上限
- 增加数据库服务器的最大连接数限制
- Hyperdrive已在高效地进行连接池管理
本地开发:
bash
undefinedUse --remote to test with actual Hyperdrive
Use --remote to test with actual Hyperdrive
npx wrangler dev --remote
npx wrangler dev --remote
Or use local connection string for development
Or use local connection string for development
(add to .dev.vars)
(add to .dev.vars)
HYPERDRIVE_CONNECTION_STRING=postgres://localhost:5432/mydb
undefinedHYPERDRIVE_CONNECTION_STRING=postgres://localhost:5432/mydb
undefined