Claude Code के साथ Using Drizzle ORM की Practical Guide
Claude Code का उपयोग करके guide to using drizzle orm, real-world code examples के साथ।
Drizzle ORM क्या है
Drizzle ORMはTypeScriptファーストの軽量ORM है।SQLに近い記法で型safeなqueryを書けるのが特徴 है।Claude Code के साथ combineれば、efficientlydatabase層 build किया जा सकता है。
スkeyマ定義
// db/schema.ts
import {
pgTable,
text,
timestamp,
boolean,
integer,
varchar,
index,
} from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
export const users = pgTable("users", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
email: varchar("email", { length: 255 }).notNull().unique(),
name: varchar("name", { length: 100 }).notNull(),
avatar: text("avatar"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
}, (table) => ({
emailIdx: index("email_idx").on(table.email),
}));
export const posts = pgTable("posts", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
title: varchar("title", { length: 255 }).notNull(),
content: text("content").notNull(),
published: boolean("published").default(false).notNull(),
authorId: text("author_id").notNull().references(() => users.id),
viewCount: integer("view_count").default(0).notNull(),
publishedAt: timestamp("published_at"),
createdAt: timestamp("created_at").defaultNow().notNull(),
}, (table) => ({
authorIdx: index("author_idx").on(table.authorId),
publishedIdx: index("published_idx").on(table.published, table.publishedAt),
}));
export const comments = pgTable("comments", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
content: text("content").notNull(),
authorId: text("author_id").notNull().references(() => users.id),
postId: text("post_id").notNull().references(() => posts.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
リレーション定義
export const usersRelations = relations(users, ({ many, one }) => ({
posts: many(posts),
comments: many(comments),
}));
export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
comments: many(comments),
}));
export const commentsRelations = relations(comments, ({ one }) => ({
author: one(users, {
fields: [comments.authorId],
references: [users.id],
}),
post: one(posts, {
fields: [comments.postId],
references: [posts.id],
}),
}));
query操作
import { drizzle } from "drizzle-orm/node-postgres";
import { eq, and, like, desc, sql, count } from "drizzle-orm";
import * as schema from "./schema";
const db = drizzle(pool, { schema });
// 挿入
async function createPost(data: {
title: string;
content: string;
authorId: string;
}) {
const [post] = await db
.insert(posts)
.values(data)
.returning();
return post;
}
// search(pageネーション付き)
async function getPosts(params: {
page?: number;
perPage?: number;
search?: string;
}) {
const { page = 1, perPage = 20, search } = params;
const conditions = [eq(posts.published, true)];
if (search) {
conditions.push(like(posts.title, `%${search}%`));
}
const [data, [{ total }]] = await Promise.all([
db
.select({
id: posts.id,
title: posts.title,
publishedAt: posts.publishedAt,
authorName: users.name,
commentCount: count(comments.id),
})
.from(posts)
.leftJoin(users, eq(posts.authorId, users.id))
.leftJoin(comments, eq(posts.id, comments.postId))
.where(and(...conditions))
.groupBy(posts.id, users.name)
.orderBy(desc(posts.publishedAt))
.limit(perPage)
.offset((page - 1) * perPage),
db
.select({ total: count() })
.from(posts)
.where(and(...conditions)),
]);
return { data, total, page, perPage };
}
// update
async function updatePost(id: string, data: Partial<typeof posts.$inferInsert>) {
const [updated] = await db
.update(posts)
.set({ ...data, updatedAt: new Date() })
.where(eq(posts.id, id))
.returning();
return updated;
}
Relational Queries API
// Prismaライクなquery
async function getPostWithRelations(id: string) {
return db.query.posts.findFirst({
where: eq(posts.id, id),
with: {
author: {
columns: { id: true, name: true, avatar: true },
},
comments: {
with: {
author: {
columns: { id: true, name: true },
},
},
orderBy: [desc(comments.createdAt)],
limit: 10,
},
},
});
}
migration
// drizzle.config.ts
import type { Config } from "drizzle-kit";
export default {
schema: "./db/schema.ts",
out: "./drizzle",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
} satisfies Config;
# migrationgenerate
npx drizzle-kit generate
# migration適用
npx drizzle-kit migrate
# Drizzle Studio(GUI)起動
npx drizzle-kit studio
Prisma との比較
| 特性 | Drizzle | Prisma |
|---|---|---|
| bundlesize | 軽量 | ややबड़ा |
| query記法 | SQL寄り | 独自API |
| エッジsupport | 優秀 | 制限あり |
| スkeyマ定義 | TypeScript | 独自DSL |
| migration | SQLgenerate | 自動management |
Claude Code सेのutilization
Drizzle ORMのimplementationをClaude Code को requestする例 है।Prismaとの比較はPrisma ORMcomplete guide、databaseintegrationके बारे मेंはSupabaseintegrationdevelopmentもदेखें。
Drizzle ORMでdatabase層 buildして。
- PostgreSQLのスkeyマ定義
- リレーション付きのCRUDquery
- pageネーションとsearch
- migrationsettings
Drizzle ORMके details के लिएDrizzle ORMofficial documentationをदेखें。Claude Codeのutilization法はofficial documentationでconfirmでき है।
Summary
Drizzle ORMはSQLに近い記法と軽量さが魅力のORM है।Claude Code का उपयोग करके、型safeなqueryとスkeyマ設計をefficientlyimplementationでき है।エッジ環境での利用にも適してい है।
मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट
बस अपना ईमेल दर्ज करें और हम तुरंत A4 एक-पृष्ठ चीटशीट PDF भेज देंगे।
हम आपकी व्यक्तिगत जानकारी की सुरक्षा करते हैं और स्पैम नहीं भेजते।
लेखक के बारे में
Masa
Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।
संबंधित लेख
Claude Code ke liye 7 CLAUDE.md templates jo aap real projects me copy kar sakte hain
Solo app, content site, API, team repo aur legacy codebase ke liye 7 practical CLAUDE.md templates, plus common failure cases.
Claude Code Approval aur Sandbox Guide | Roz ke kaam ke liye safe settings
Claude Code me allow, ask, deny aur sandbox ko kaise baantna chahiye - practical settings, hooks aur real workflow examples ke saath.
Claude Code की सम्पूर्ण शुरुआती गाइड 2026 | शून्य से प्रोफेशनल उपयोग तक 7 स्टेप्स में
पहली बार Claude Code उपयोग करने वालों के लिए पूरी गाइड। इंस्टॉलेशन से लेकर असली डेवलपमेंट वर्कफ्लो में शामिल करने तक — Masa के शुरुआती अनुभव के आधार पर।