Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

PostgreSQL に接続する

最終更新 Markdown で表示Agent セットアップ

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:password@database.host.example.com:5432/databasenamehere"

上のコマンドは Hyperdrive の ID を出力します。Workers プロジェクトの Wrangler 設定ファイル にこの ID を設定します。

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

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

これにより、Worker 内で Hyperdrive が動的な接続文字列を生成し、既存のデータベースドライバーへ渡せます。データベースドライバーを Hyperdrive と組み合わせる方法は、ドライバーの例 を参照してください。

主要なデータベースプロバイダーで Hyperdrive を設定する手順は、Examples ドキュメント を参照してください。

対応ドライバー

Hyperdrive は Workers の TCP ソケット対応 を使い、データベースへの TCP 接続を実現します。次の表は、対応するデータベースドライバーと、Hyperdrive で動作する最小バージョンです。

ドライバー ドキュメント 必要な最小バージョン 備考
node-postgres - pg(推奨) node-postgres - pg documentation pg@8.13.0 8.11.4 には URL 解析のバグがあり、動作しません。8.11.5 で修正されています。compatibility_flags = ["nodejs_compat"]compatibility_date = "2024-09-23" が必要です。Node.js 互換性 を参照してください。wrangler 3.78.7 以降が必要です。
Postgres.js Postgres.js documentation postgres@3.4.4 Workers と Pages の両方で使えます。
Drizzle Drizzle documentation 0.26.2^
Kysely Kysely documentation 0.26.3^
rust-postgres rust-postgres documentation v0.19.8 最高の性能には query_typed メソッドを使います。

^ 印のライブラリは依存関係として node-postgres を使います。

掲載していないドライバーや ORM も使える場合があります。この一覧はすべてを網羅していません。

データベースドライバーと Node.js 互換性

Postgres.js を含むデータベースドライバーには Node.js 互換性 が必要で、Workers プロジェクトで設定する必要があります。

互換性日付が 2026-08-04 以降の場合、Workers と Pages プロジェクトでは nodejs_compatnodejs_compat_v2 がデフォルトで有効になります。組み込みのランタイム API とポリフィルは、追加の設定なしで使えます。これらの互換性日付では、これらのフラグは使われません。既存プロジェクトは、互換性日付を更新するときにフラグを削除する必要はありません。

互換性日付が 2026-08-04 より前の場合は、オプトインするために Wrangler 設定ファイルnodejs_compat 互換性フラグ を追加します。

{
	"compatibility_flags": [
		"nodejs_compat"
	]
}
compatibility_flags = [ "nodejs_compat" ]

互換性日付が 2026-08-04 以降で Node.js 互換 を完全にオフにするには、有効化フラグがあれば削除します。次に no_nodejs_compatno_nodejs_compat_v2 の両方を追加します。設定例は Node.js 互換性フラグ を参照してください。

ドライバーの例

次の例では、次の手順を示します。

  1. データベースドライバーでデータベースクライアントを作成します。
  2. Hyperdrive の接続文字列を渡してデータベースへ接続します。
  3. Hyperdrive 経由でデータベースを照会します。

node-postgres / pg

node-postgres ドライバーをインストールします。

npm i pg@>8.16.3

TypeScript を使う場合は、型定義パッケージもインストールします。

npm i -D @types/pg

必要な Node.js 互換性フラグと Hyperdrive バインディングを、wrangler.jsonc ファイルに追加します。

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

[[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

必要な Node.js 互換性フラグと Hyperdrive バインディングを wrangler.jsonc に追加します。

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

[[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 からの接続を識別する

Postgres データベースサーバー上で、Hyperdrive からのアクティブな接続を識別するには:

  • Hyperdrive からデータベースへの接続は、pg_stat_activity テーブルの application_nameCloudflare Hyperdrive として表示されます。
  • SELECT DISTINCT usename, application_name FROM pg_stat_activity WHERE application_name = 'Cloudflare Hyperdrive' を実行すると、Hyperdrive が現在データベースへの接続を保持しているかどうかを確認できます。

次のステップ

役に立ちましたか?