コンテンツにスキップ

AWS RDSおよびAuroraに接続する

HyperdriveをAWS RDSまたはAuroraデータベースインスタンスに接続します。

この例では、HyperdriveをAmazon Relational Database Service(Amazon RDS)PostgresまたはAmazon Auroraデータベースインスタンスに接続する方法を示します。

1. Hyperdriveのアクセスを許可する

Hyperdriveがデータベースに接続できるようにするには、Hyperdriveに有効なユーザー資格情報とネットワークアクセスがあることを確認する必要があります。

AWSコンソール

AWSコンソールでインスタンスを作成または変更する際には:

  1. DBクラスター識別子やその他の設定を構成します。
  2. 設定 > 資格情報設定の下で、マスターユーザー名マスターパスワードをメモします。
  3. 接続性ヘッダーの下で、パブリックアクセスはいに設定されていることを確認します。
  4. データベースインスタンスがリッスンするポート(デフォルト:PostgreSQLインスタンスの場合は5432)へのパブリックインターネットアクセスを許可する既存のVPCセキュリティグループを選択します。
  5. データベースを作成を選択します。

データベースエンドポイントを取得する(Aurora)

Hyperdriveが接続するためのデータベースエンドポイント(ホスト名)を取得するには:

  1. AWSコンソールのRDSの下にあるデータベースビューに移動します。
  2. Hyperdriveが接続するデータベースを選択します。
  3. エンドポイントヘッダーの下で、Writerタイプのエンドポイント名ポートをメモします。

データベースエンドポイントを取得する(RDS PostgreSQL)

通常のRDSインスタンス(非Aurora)の場合、データベースのエンドポイントとポートを取得する必要があります:

  1. AWSコンソールのRDSの下にあるデータベースビューに移動します。
  2. Hyperdriveが接続するデータベースを選択します。
  3. 接続性とセキュリティヘッダーの下で、エンドポイントポートをメモします。

エンドポイントはYOUR_DATABASE_NAME.cpuo5rlli58m.AWS_REGION.rds.amazonaws.comのようになり、ポートはデフォルトで5432になります。

2. ユーザーを作成する

データベースが作成されたら、Hyperdriveが接続するためのユーザーを作成する必要があります。初期データベース作成時に設定したマスターユーザー名を使用することもできますが、ベストプラクティスとしては権限の少ないユーザーを作成することをお勧めします。

新しいユーザーを作成するには、データベースにログインし、CREATE ROLEコマンドを使用します:

Terminal window
# データベースにログイン
psql postgresql://MASTER_USERNAME:MASTER_PASSWORD@ENDPOINT_NAME:PORT/database_name

次のSQL文を実行します:

-- Hyperdrive用のロールを作成
CREATE ROLE hyperdrive;
-- Hyperdriveが接続できるようにする
GRANT CONNECT ON DATABASE postgres TO hyperdrive;
-- hyperdriveロールにデータベース権限を付与
GRANT ALL PRIVILEGES ON DATABASE postgres to hyperdrive;
-- Hyperdriveがログインするための特定のユーザーを作成
CREATE ROLE hyperdrive_user LOGIN PASSWORD 'sufficientlyRandomPassword';
-- この新しいユーザーにhyperdriveロールの権限を付与
GRANT hyperdrive to hyperdrive_user;

PostgreSQLにおけるユーザーロールに関するAWSのドキュメントを参照して、詳細を確認してください。

データベースユーザー、パスワード、データベースエンドポイント(ホスト名とポート)、およびデータベース名(デフォルト:postgres)があれば、Hyperdriveを設定できます。

3. データベース構成を作成する

To configure Hyperdrive, you will need:

  • The IP address (or hostname) and port of your database.
  • The database username (for example, hyperdrive-demo) you configured in a previous step.
  • The password associated with that username.
  • The name of the database you want Hyperdrive to connect to. For example, postgres.

Hyperdrive accepts the combination of these parameters in the common connection string format used by database drivers:

postgres://USERNAME:PASSWORD@HOSTNAME_OR_IP_ADDRESS:PORT/database_name

Most database providers will provide a connection string you can directly copy-and-paste directly into Hyperdrive.

To create a Hyperdrive configuration with the Wrangler CLI, open your terminal and run the following command. Replace <NAME_OF_HYPERDRIVE_CONFIG> with a name for your Hyperdrive configuration and paste the connection string provided from your database host, or replace user, password, HOSTNAME_OR_IP_ADDRESS, port, and database_name placeholders with those specific to your database:

Terminal window
npx wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string="postgres://user:password@HOSTNAME_OR_IP_ADDRESS:PORT/database_name"

This command outputs a binding for wrangler.toml:

name = "hyperdrive-example"
main = "src/index.ts"
compatibility_date = "2024-08-21"
compatibility_flags = ["nodejs_compat"]
# Pasted from the output of `wrangler hyperdrive create <NAME_OF_HYPERDRIVE_CONFIG> --connection-string=[...]` above.
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<ID OF THE CREATED HYPERDRIVE CONFIGURATION>"

Install the driver:

Terminal window
npm install postgres

Copy the below Worker code, which passes the connection string generated from env.HYPERDRIVE.connectionString directly to the driver.

import postgres from 'postgres'
export interface Env {
// If you set another name in wrangler.toml as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
console.log(JSON.stringify(env));
// Create a database client that connects to our 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 result = await sql`SELECT * FROM pg_tables;`
// Returns result rows as JSON
return Response.json({ result: result });
} catch (e) {
console.log(e);
return Response.json({ error: e.message }, { status: 500 });
}
},
} satisfies ExportedHandler<Env>;

Next steps