hyperdrive

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hyperdrive

Hyperdrive

Accelerate access to existing PostgreSQL and MySQL databases with connection pooling and caching.
借助连接池与缓存功能,加速访问现有PostgreSQL和MySQL数据库。

FIRST: Create Hyperdrive Configuration

第一步:创建Hyperdrive配置

bash
undefined
bash
undefined

Create 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

快速参考

OperationAPI
Get connection string
env.HYPERDRIVE.connectionString
Connect with Postgres.js
postgres(env.HYPERDRIVE.connectionString)
Query with Postgres.js
await sql`SELECT * FROM users`
No cleanup neededHyperdrive handles connection pooling—don't call
sql.end()
List configs
npx wrangler hyperdrive list
Get config details
npx wrangler hyperdrive get <ID>
Update config
npx wrangler hyperdrive update <ID> --origin-password=<NEW_PASSWORD>
Delete config
npx wrangler hyperdrive delete <ID>
操作API
查询连接字符串
env.HYPERDRIVE.connectionString
使用Postgres.js连接
postgres(env.HYPERDRIVE.connectionString)
使用Postgres.js执行查询
await sql`SELECT * FROM users`
无需手动清理Hyperdrive会处理连接池管理——请勿调用
sql.end()
列出所有配置
npx wrangler hyperdrive list
获取配置详情
npx wrangler hyperdrive get <ID>
更新配置
npx wrangler hyperdrive update <ID> --origin-password=<NEW_PASSWORD>
删除配置
npx wrangler hyperdrive delete <ID>

Connect with Postgres.js

使用Postgres.js连接

Install dependencies first:
bash
npm install postgres
Code:
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
sql.end()
or close connections manually.
  • 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 connection

Supported Drivers

支持的驱动

DriverPackageNotes
Postgres.js
postgres
Recommended - 3.4.5 or later
node-postgres
pg
Widely used, works well
Drizzle ORM
drizzle-orm
Use with postgres driver
Prisma
@prisma/client
Add
?connection_limit=1
to connection string
See references/drivers.md for detailed driver integration examples.
驱动包名说明
Postgres.js
postgres
推荐使用 - 版本3.4.5及以上
node-postgres
pg
应用广泛,兼容性良好
Drizzle ORM
drizzle-orm
需搭配postgres驱动使用
Prisma
@prisma/client
需在连接字符串中添加
?connection_limit=1
如需查看详细的驱动集成示例,请参阅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
?connection_limit=1
to prevent connection pool exhaustion:
typescript
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=1
以避免连接池耗尽:
typescript
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
undefined
Hyperdrive同样支持MySQL数据库:
bash
undefined

Create MySQL Hyperdrive config

Create MySQL Hyperdrive config

npx wrangler hyperdrive create my-mysql
--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"

```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
undefined
Hyperdrive会自动缓存查询结果。可在创建配置时自定义缓存行为:
bash
undefined

Default: 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

**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 table
npx wrangler hyperdrive create my-db
--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

最佳实践

  1. Use Postgres.js 3.4.5+ - Best compatibility and performance with Hyperdrive
  2. Never call sql.end() - Hyperdrive manages connection lifecycle
  3. One config per database - Reuse the same Hyperdrive binding across Workers
  4. Use Prisma carefully - Always add
    ?connection_limit=1
    to the connection string
  5. Test locally with wrangler dev - Use
    --remote
    flag to connect through Hyperdrive
  6. Store credentials securely - Never commit connection strings; use environment variables
  7. Monitor with observability - Enable in
    wrangler.jsonc
    to track query performance
  8. Connection string format - Use standard Postgres/MySQL connection string format
  1. 使用Postgres.js 3.4.5及以上版本 - 与Hyperdrive的兼容性和性能最佳
  2. 请勿调用sql.end() - Hyperdrive会管理连接的生命周期
  3. 每个数据库对应一个配置 - 在多个Workers之间复用同一个Hyperdrive绑定
  4. 谨慎使用Prisma - 务必在连接字符串中添加
    ?connection_limit=1
  5. 使用wrangler dev进行本地测试 - 使用
    --remote
    参数通过Hyperdrive连接
  6. 安全存储凭证 - 请勿将连接字符串提交至版本控制系统,应使用环境变量
  7. 通过可观测性工具监控 - 在
    wrangler.jsonc
    中启用该功能以追踪查询性能
  8. 连接字符串格式规范 - 使用标准的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
    ?connection_limit=1
    to the connection string
  • 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
undefined

Use --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
undefined
HYPERDRIVE_CONNECTION_STRING=postgres://localhost:5432/mydb
undefined