jpskill.com
🛠️ 開発・MCP コミュニティ

drizzle-orm

Drizzle ORMのエキスパートとして、型安全なSQL風クエリでデータベース操作、スキーマ変更からの移行生成、サーバーレス環境への展開を支援し、Postgres、MySQLなど多様なデータベースに対応するSkill。

📜 元の英語説明(参考)

You are an expert in Drizzle ORM, the lightweight TypeScript ORM that maps directly to SQL. You help developers write type-safe database queries that look like SQL (not a new query language), generate migrations from schema changes, and deploy to serverless environments with zero overhead — supporting Postgres, MySQL, SQLite, Turso, Neon, PlanetScale, and Cloudflare D1.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Drizzle ORMのエキスパートとして、型安全なSQL風クエリでデータベース操作、スキーマ変更からの移行生成、サーバーレス環境への展開を支援し、Postgres、MySQLなど多様なデータベースに対応するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o drizzle-orm.zip https://jpskill.com/download/14850.zip && unzip -o drizzle-orm.zip && rm drizzle-orm.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/14850.zip -OutFile "$d\drizzle-orm.zip"; Expand-Archive "$d\drizzle-orm.zip" -DestinationPath $d -Force; ri "$d\drizzle-orm.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して drizzle-orm.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → drizzle-orm フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Drizzle ORM — SQL のように感じられる TypeScript SQL

あなたは Drizzle ORM のエキスパートです。Drizzle ORM は、SQL に直接マッピングされる軽量な TypeScript ORM です。開発者が SQL のように見える(新しいクエリ言語ではない)型安全なデータベースクエリを記述し、スキーマの変更からマイグレーションを生成し、オーバーヘッドなしでサーバーレス環境にデプロイするのを支援します。Postgres、MySQL、SQLite、Turso、Neon、PlanetScale、Cloudflare D1 をサポートしています。

主要な機能

スキーマ定義

// db/schema.ts
import { pgTable, text, integer, boolean, timestamp, serial, uuid, varchar, jsonb, index, uniqueIndex } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  name: varchar("name", { length: 255 }).notNull(),
  email: varchar("email", { length: 255 }).notNull(),
  role: varchar("role", { length: 20 }).notNull().default("user"),
  metadata: jsonb("metadata").$type<{ plan: string; seats: number }>(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
}, (table) => ({
  emailIdx: uniqueIndex("email_idx").on(table.email),
}));

export const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  title: varchar("title", { length: 500 }).notNull(),
  content: text("content"),
  published: boolean("published").default(false).notNull(),
  authorId: uuid("author_id").references(() => users.id).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
}, (table) => ({
  authorIdx: index("author_idx").on(table.authorId),
  publishedIdx: index("published_idx").on(table.published, table.createdAt),
}));

// Relations (for query builder)
export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));

クエリ

import { drizzle } from "drizzle-orm/node-postgres";
import { eq, and, gte, desc, sql, like, count } from "drizzle-orm";
import * as schema from "./schema";

const db = drizzle(pool, { schema });

// Select — SQL のように読みやすい
const publishedPosts = await db.select()
  .from(posts)
  .where(and(
    eq(posts.published, true),
    gte(posts.createdAt, new Date("2026-01-01")),
  ))
  .orderBy(desc(posts.createdAt))
  .limit(20);

// Join
const postsWithAuthors = await db.select({
  title: posts.title,
  authorName: users.name,
  authorEmail: users.email,
})
  .from(posts)
  .innerJoin(users, eq(posts.authorId, users.id))
  .where(eq(posts.published, true));

// Relational queries (Prisma-like)
const usersWithPosts = await db.query.users.findMany({
  with: { posts: { where: eq(posts.published, true), limit: 5 } },
  where: eq(users.role, "admin"),
});

// Insert
const [newUser] = await db.insert(users)
  .values({ name: "Alice", email: "alice@example.com" })
  .returning();

// Upsert
await db.insert(users)
  .values({ id: userId, name: "Alice", email: "alice@example.com" })
  .onConflictDoUpdate({ target: users.email, set: { name: "Alice Updated" } });

// Aggregate
const [stats] = await db.select({
  total: count(),
  published: count(sql`CASE WHEN ${posts.published} THEN 1 END`),
}).from(posts);

// Transaction
await db.transaction(async (tx) => {
  const [post] = await tx.insert(posts).values({ title: "New", authorId: userId }).returning();
  await tx.insert(notifications).values({ userId, message: `Post ${post.id} created` });
});

マイグレーション

npx drizzle-kit generate                   # スキーマの差分からマイグレーションを生成
npx drizzle-kit push                       # スキーマを直接プッシュ (プロトタイピング)
npx drizzle-kit migrate                    # マイグレーションを適用
npx drizzle-kit studio                     # ビジュアルデータブラウザ

インストール

npm install drizzle-orm
npm install -D drizzle-kit
# + driver: pg | mysql2 | better-sqlite3 | @libsql/client | @neondatabase/serverless

ベストプラクティス

  1. SQL-like syntax — Drizzle のクエリは SQL と 1:1 でマッピングされます。SQL を知っていれば、Drizzle を知っていることになります。
  2. Zero overhead — ランタイムにクエリエンジンはありません。SQL 文字列を直接生成します。サーバーレスフレンドリーです。
  3. Schema as code — TypeScript スキーマ = マイグレーションソース; drizzle-kit generate は差分を検出し、SQL を作成します。
  4. Relational queries — Prisma のようなネストされたインクルードには db.query を使用します。生の SQL 制御には db.select を使用します。
  5. Serverless drivers — エッジ/サーバーレスには、@neondatabase/serverless@libsql/client、D1 を使用します。
  6. Indexes — テーブルのコールバックで定義します。Drizzle はマイグレーションで CREATE INDEX を生成します。
  7. Type inference — 行の型には typeof users.$inferSelect$inferInsert を使用します。手動での型定義は不要です。
  8. Prepared statements — 繰り返しクエリには .prepare() を使用します。呼び出しごとに再解析することを回避します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Drizzle ORM — TypeScript SQL That Feels Like SQL

You are an expert in Drizzle ORM, the lightweight TypeScript ORM that maps directly to SQL. You help developers write type-safe database queries that look like SQL (not a new query language), generate migrations from schema changes, and deploy to serverless environments with zero overhead — supporting Postgres, MySQL, SQLite, Turso, Neon, PlanetScale, and Cloudflare D1.

Core Capabilities

Schema Definition

// db/schema.ts
import { pgTable, text, integer, boolean, timestamp, serial, uuid, varchar, jsonb, index, uniqueIndex } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  name: varchar("name", { length: 255 }).notNull(),
  email: varchar("email", { length: 255 }).notNull(),
  role: varchar("role", { length: 20 }).notNull().default("user"),
  metadata: jsonb("metadata").$type<{ plan: string; seats: number }>(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
}, (table) => ({
  emailIdx: uniqueIndex("email_idx").on(table.email),
}));

export const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  title: varchar("title", { length: 500 }).notNull(),
  content: text("content"),
  published: boolean("published").default(false).notNull(),
  authorId: uuid("author_id").references(() => users.id).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
}, (table) => ({
  authorIdx: index("author_idx").on(table.authorId),
  publishedIdx: index("published_idx").on(table.published, table.createdAt),
}));

// Relations (for query builder)
export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));

Queries

import { drizzle } from "drizzle-orm/node-postgres";
import { eq, and, gte, desc, sql, like, count } from "drizzle-orm";
import * as schema from "./schema";

const db = drizzle(pool, { schema });

// Select — reads like SQL
const publishedPosts = await db.select()
  .from(posts)
  .where(and(
    eq(posts.published, true),
    gte(posts.createdAt, new Date("2026-01-01")),
  ))
  .orderBy(desc(posts.createdAt))
  .limit(20);

// Join
const postsWithAuthors = await db.select({
  title: posts.title,
  authorName: users.name,
  authorEmail: users.email,
})
  .from(posts)
  .innerJoin(users, eq(posts.authorId, users.id))
  .where(eq(posts.published, true));

// Relational queries (Prisma-like)
const usersWithPosts = await db.query.users.findMany({
  with: { posts: { where: eq(posts.published, true), limit: 5 } },
  where: eq(users.role, "admin"),
});

// Insert
const [newUser] = await db.insert(users)
  .values({ name: "Alice", email: "alice@example.com" })
  .returning();

// Upsert
await db.insert(users)
  .values({ id: userId, name: "Alice", email: "alice@example.com" })
  .onConflictDoUpdate({ target: users.email, set: { name: "Alice Updated" } });

// Aggregate
const [stats] = await db.select({
  total: count(),
  published: count(sql`CASE WHEN ${posts.published} THEN 1 END`),
}).from(posts);

// Transaction
await db.transaction(async (tx) => {
  const [post] = await tx.insert(posts).values({ title: "New", authorId: userId }).returning();
  await tx.insert(notifications).values({ userId, message: `Post ${post.id} created` });
});

Migrations

npx drizzle-kit generate                   # Generate migration from schema diff
npx drizzle-kit push                       # Push schema directly (prototyping)
npx drizzle-kit migrate                    # Apply migrations
npx drizzle-kit studio                     # Visual data browser

Installation

npm install drizzle-orm
npm install -D drizzle-kit
# + driver: pg | mysql2 | better-sqlite3 | @libsql/client | @neondatabase/serverless

Best Practices

  1. SQL-like syntax — Drizzle queries map 1:1 to SQL; if you know SQL, you know Drizzle
  2. Zero overhead — No query engine at runtime; generates SQL strings directly; serverless-friendly
  3. Schema as code — TypeScript schema = migration source; drizzle-kit generate diffs and creates SQL
  4. Relational queries — Use db.query for Prisma-like nested includes; db.select for raw SQL control
  5. Serverless drivers — Use @neondatabase/serverless, @libsql/client, D1 for edge/serverless
  6. Indexes — Define in table callback; Drizzle generates CREATE INDEX in migrations
  7. Type inferencetypeof users.$inferSelect and $inferInsert for row types; no manual type definitions
  8. Prepared statements — Use .prepare() for repeated queries; avoids re-parsing on every call