关于 drizzle-queries
drizzle-queries 是面向使用 Drizzle ORM 和 Postgres 的开发者的查询实践技能,涵盖数据操作、关系查询及新增表的迁移流程。
主要功能
- 01类型安全的 Postgres 查询
- 02选择、插入、更新和删除
- 03关系数据查询
- 04添加表并执行迁移
适用场景
- 01读取或修改应用数据
- 02按关联关系获取聊天及消息
- 03为功能添加数据库表
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ andrelandgraf/ fullstackrecipes --skill drizzle-queries安装后在 Claude Code 中输入/drizzle-queries确认已加载。
详细介绍
Drizzle 查询
使用 Drizzle ORM 编写类型安全的 Postgres 查询。
前置条件
请先完成以下设置教程:
- Neon + Drizzle 设置
查询
从 @/lib/db/client 导入 db,从 drizzle-orm 导入运算符。查询单行时,使用 .limit(1),然后取 rows[0]。
import { db } from "@/lib/db/client";
import { chats } from "@/lib/chat/schema";
import { eq, desc } from "drizzle-orm";
const allChats = await db.select().from(chats);
const userChats = await db
.select()
.from(chats)
.where(eq(chats.userId, userId))
.orderBy(desc(chats.createdAt));
const chat = await db
.select()
.from(chats)
.where(eq(chats.id, chatId))
.limit(1)
.then((rows) => rows[0]);
插入
需要返回插入的行时,使用 .returning()。
const [newChat] = await db
.insert(chats)
.values({ userId, title: "New Chat" })
.returning();
await db.insert(messages).values([
{ chatId, role: "user", content: "Hello" },
{ chatId, role: "assistant", content: "Hi there!" },
]);
更新
await db
.update(chats)
.set({ title: "Updated Title" })
.where(eq(chats.id, chatId));
删除
await db.delete(chats).where(eq(chats.id, chatId));
关系查询
对于关系查询,使用 db.query.<table>,而非手动联接。
const chatWithMessages = await db.query.chats.findFirst({
where: eq(chats.id, chatId),
with: {
messages: {
orderBy: (messages, { asc }) => [asc(messages.createdAt)],
},
},
});
添加表
将 schema 放在功能对应的库文件夹中,在共享客户端中注册,然后执行迁移。
// src/lib/feature/schema.ts
import { pgTable, text, uuid, timestamp } from "drizzle-orm/pg-core";
export const items = pgTable("items", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// src/lib/db/client.ts
import * as itemSchema from "@/lib/feature/schema";
const schema = { ...authSchema, ...chatSchema, ...itemSchema };
bun run db:generate
bun run db:migrate
参考资料
评论
支持 Markdown