跳转到内容
搜索文档

连接 PostgreSQL

最后更新 查看 MarkdownAgent 设置

Hyperdrive 支持 PostgreSQL 及 PostgreSQL 兼容数据库、常用驱动以及使用这些驱动的对象关系映射(ORM)库。

创建 Hyperdrive

要创建连接现有 PostgreSQL 数据库的 Hyperdrive,使用 wrangler CLI 或 Cloudflare 仪表板

使用 wrangler 时,将 --connection-string 的占位值替换为数据库连接字符串:

# wrangler v3.11 and above required
npx wrangler hyperdrive create my-first-hyperdrive --connection-string="postgres://user:[email protected]:5432/databasenamehere"

上述命令会输出 Hyperdrive ID,需在 Workers 项目的 Wrangler 配置文件 中设置:

wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-17",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"

这使 Hyperdrive 在 Worker 内生成动态连接字符串,可传给现有数据库驱动。请参阅驱动示例了解如何配合 Hyperdrive 设置数据库驱动。

分步指南请参阅示例文档,了解如何与多个热门数据库提供商设置 Hyperdrive。

支持的驱动

Hyperdrive 使用 Workers TCP socket 支持 建立到数据库的 TCP 连接。下表列出支持的驱动及 Hyperdrive 所需的最低版本:

驱动 文档 最低版本要求 说明
node-postgres - pg(推荐) node-postgres - pg 文档 [email protected] 8.11.4 存在 URL 解析 bug 无法使用。8.11.5 已修复。需要 compatibility_flags = ["nodejs_compat"]compatibility_date = "2024-09-23" — 请参阅 Node.js 兼容性。需要 wrangler 3.78.7 或更高版本。
Postgres.js Postgres.js 文档 [email protected] 支持 Workers 和 Pages。
Drizzle Drizzle 文档 0.26.2^
Kysely Kysely 文档 0.26.3^
rust-postgres rust-postgres 文档 v0.19.8 为获得最佳性能,使用 query_typed 方法。

^ 标记的库使用 node-postgres 作为依赖。

未列出的其他驱动和 ORM 也可能受支持:此列表并非详尽。

数据库驱动与 Node.js 兼容性

数据库驱动(包括 Postgres.js)需要 Node.js 兼容性,须为 Workers 项目配置。

要为 Worker 或 Pages 项目启用内置运行时 API 和 polyfill,请在你的 Wrangler 配置文件中添加 nodejs_compat 兼容性标志,并将兼容性日期设置为 2024 年 9 月 23 日或更高版本。这将为 Workers 项目启用 Node.js 兼容性

{
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-17"
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"

驱动示例

以下示例展示如何:

  1. 使用数据库驱动创建数据库客户端。
  2. 传入 Hyperdrive 连接字符串并连接数据库。
  3. 通过 Hyperdrive 查询数据库。

node-postgres / pg

安装 node-postgres 驱动:

npm i pg@>8.16.3

若使用 TypeScript,安装类型包:

npm i -D @types/pg

wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:

wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-17",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"

创建新的 Client 实例并传入 Hyperdrive connectionString

// filepath: src/index.ts
import { Client } from "pg";

export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext,
	): Promise<Response> {
		// Create a new client instance for each request. Hyperdrive maintains the
		// underlying database connection pool, so creating a new client is fast.
		const client = new Client({
			connectionString: env.HYPERDRIVE.connectionString,
		});

		try {
			// Connect to the database
			await client.connect();

			// Perform a simple query
			const result = await client.query("SELECT * FROM pg_tables");

			return Response.json({
				success: true,
				result: result.rows,
			});
		} catch (error: any) {
			console.error("Database error:", error.message);

			return new Response("Internal error occurred", { status: 500 });
		}
	},
};

Postgres.js

安装 Postgres.js

npm i postgres@>3.4.5

wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:

wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-08-17",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"

创建通过 Hyperdrive 连接 PostgreSQL 数据库的 Worker:

// filepath: src/index.ts
import postgres from "postgres";

export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext,
	): Promise<Response> {
		// Create a database client that connects to your database via Hyperdrive.
		// Hyperdrive maintains the underlying database connection pool,
		// so creating a new client on each request is fast and recommended.
		const sql = postgres(env.HYPERDRIVE.connectionString, {
			// Limit the connections for the Worker request to 5 due to Workers' limits on concurrent external connections
			max: 5,
			// If you are not using array types in your Postgres schema, disable `fetch_types` to avoid an additional round-trip (unnecessary latency)
			fetch_types: false,

			// This is set to true by default, but certain query generators such as Kysely or queries using sql.unsafe() will set this to false. Hyperdrive will not cache prepared statements when this option is set to false and will require additional round-trips.  
			prepare: true,
		});

		try {
			// A very simple test query
			const result = await sql`select * from pg_tables`;

			// Return result rows as JSON
			return Response.json({ success: true, result: result });
		} catch (e: any) {
			console.error("Database error:", e.message);

			return Response.error();
		}
	},
} satisfies ExportedHandler<Env>;

识别来自 Hyperdrive 的连接

要识别 Hyperdrive 到 Postgres 数据库服务器的活动连接:

  • Hyperdrive 到数据库的连接在 pg_stat_activity 表的 application_name 中显示为 Cloudflare Hyperdrive
  • 运行 SELECT DISTINCT usename, application_name FROM pg_stat_activity WHERE application_name = 'Cloudflare Hyperdrive' 可查看 Hyperdrive 是否当前保持到数据库的连接。

后续步骤

这篇文档对您有帮助吗?