Skip to content

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

Drizzle ORM

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

Drizzle ORM は、型安全を重視した軽量な TypeScript ORM です。この例では、Workers アプリケーションで Cloudflare Hyperdrive 経由の PostgreSQL に Drizzle ORM を使う方法を示します。

前提条件

1. Drizzle をインストールする

Drizzle ORM と、node-postgrespg)ドライバーなどの依存関係をインストールします。

npm i drizzle-orm pg dotenv
npm i -D drizzle-kit tsx @types/pg @types/node

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

2. Drizzle を設定する

2.1. スキーマを定義する

Drizzle ORM では、生の SQL を書かず、TypeScript でスキーマを定義します。

  1. /src//db/ フォルダーを作成します。

  2. schema.ts ファイルを作成します。

  3. schema.ts で、次のように users テーブルを定義します。

    src/db/schema.tsts
    // src/db/schema.ts
    import { pgTable, serial, varchar, timestamp } from "drizzle-orm/pg-core";
    
    export const users = pgTable("users", {
    	id: serial("id").primaryKey(),
    	name: varchar("name", { length: 255 }).notNull(),
    	email: varchar("email", { length: 255 }).notNull().unique(),
    	createdAt: timestamp("created_at").defaultNow(),
    });

2.2. Hyperdrive で Drizzle ORM をデータベースに接続する

Drizzle ORM を使うときは、データベース向けの Hyperdrive 設定を使います。

index.ts を次のように記述します。

src/index.tsts
// src/index.ts
import { Client } from "pg";
import { drizzle } from "drizzle-orm/node-postgres";
import { users } from "./db/schema";

export interface Env {
	HYPERDRIVE: Hyperdrive;
}

export default {
	async fetch(request, env, ctx): Promise<Response> {
		// Create a new client instance for each request.
		const client = new Client({
			connectionString: env.HYPERDRIVE.connectionString,
		});

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

		// Create the Drizzle client with the node-postgres connection
		const db = drizzle(client);

		// Sample query to get all users
		const allUsers = await db.select().from(users);

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

2.3. マイグレーション用に Drizzle-Kit を設定する(任意)

スキーマに基づく SQL マイグレーションは、Drizzle Kit CLI で生成して実行できます。追加の手順は Drizzle ORM のドキュメント を参照してください。

  1. プロジェクトのルートフォルダーに .env ファイルを作成し、データベースの接続文字列を追加します。Drizzle Kit CLI はこの接続文字列を使って、マイグレーションの作成と適用を行います。

    .envtoml
    # .env
    # Replace with your direct database connection string
    DATABASE_URL='postgres://user:[email protected]/database-name'
  2. プロジェクトのルートフォルダーに drizzle.config.ts を作成し、Drizzle Kit を設定して次の内容を追加します。

    drizzle.config.tsts
    // drizzle.config.ts
    import "dotenv/config";
    import { defineConfig } from "drizzle-kit";
    export default defineConfig({
    	out: "./drizzle",
    	schema: "./src/db/schema.ts",
    	dialect: "postgresql",
    	dbCredentials: {
    		url: process.env.DATABASE_URL!,
    	},
    });
  3. スキーマファイルに合わせてデータベースのマイグレーションファイルを生成し、データベースにマイグレーションを適用します。

    次の 2 つのコマンドを実行します。

    npx drizzle-kit generate
    No config path provided, using default 'drizzle.config.ts'
    Reading config file 'drizzle.config.ts'
    1 tables
    users 4 columns 0 indexes 0 fks
    
    [✓] Your SQL migration file ➜ drizzle/0000_mysterious_queen_noir.sql 🚀
    npx drizzle-kit migrate
    No config path provided, using default 'drizzle.config.ts'
    Reading config file 'drizzle.config.ts'
    Using 'postgres' driver for database querying

3. Worker をデプロイする

Worker をデプロイします。

npx wrangler deploy

次のステップ

役に立ちましたか?