mcpField
U
using-drizzle-queries

using-drizzle-queries

github.com/andrelandgraf数据与数据库23135 次安装20 周前更新
代码仓库

关于 using-drizzle-queries

using-drizzle-queries 是一项参考技能,介绍如何使用 Drizzle ORM 编写类型安全的数据库查询,涵盖常见数据操作、关联查询,以及新增表和迁移的步骤。

主要功能

  1. 01Select、insert、update 和 delete 查询
  2. 02关联查询模式
  3. 03创建表结构
  4. 04注册结构并执行迁移

适用场景

  1. 01编写带筛选条件的数据库查询
  2. 02通过关联读取相关记录
  3. 03向项目结构中添加数据表
  4. 04生成并运行数据库迁移

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/andrelandgraf/fullstackrecipes --skill using-drizzle-queries

安装后在 Claude Code 中输入/using-drizzle-queries确认已加载。

详细介绍

使用 Drizzle

使用 Drizzle ORM 编写类型安全的数据库查询。涵盖查询、插入、更新、删除、关系查询以及添加新表。

实现 Drizzle 的使用

使用 Drizzle ORM 编写类型安全的数据库查询。涵盖查询、插入、更新、删除、关系查询以及添加新表。

参见:


编写查询

使用 Drizzle 的查询 API 执行类型安全的数据库操作:

import { db } from "@/lib/db/client";
import { chats } from "@/lib/chat/schema";
import { eq, desc } from "drizzle-orm";

// Select all
const allChats = await db.select().from(chats);

// Select with filter
const userChats = await db
  .select()
  .from(chats)
  .where(eq(chats.userId, userId))
  .orderBy(desc(chats.createdAt));

// Select single record
const chat = await db
  .select()
  .from(chats)
  .where(eq(chats.id, chatId))
  .limit(1)
  .then((rows) => rows[0]);
插入数据
import { db } from "@/lib/db/client";
import { chats } from "@/lib/chat/schema";

// Insert single record
const [newChat] = await db
  .insert(chats)
  .values({
    userId,
    title: "New Chat",
  })
  .returning();

// Insert multiple records
await db.insert(messages).values([
  { chatId, role: "user", content: "Hello" },
  { chatId, role: "assistant", content: "Hi there!" },
]);
更新数据
import { db } from "@/lib/db/client";
import { chats } from "@/lib/chat/schema";
import { eq } from "drizzle-orm";

await db
  .update(chats)
  .set({ title: "Updated Title" })
  .where(eq(chats.id, chatId));
删除数据
import { db } from "@/lib/db/client";
import { chats } from "@/lib/chat/schema";
import { eq } from "drizzle-orm";

await db.delete(chats).where(eq(chats.id, chatId));
使用关系查询

对于涉及关系的查询,请使用查询 API:

import { db } from "@/lib/db/client";

const chatWithMessages = await db.query.chats.findFirst({
  where: eq(chats.id, chatId),
  with: {
    messages: {
      orderBy: (messages, { asc }) => [asc(messages.createdAt)],
    },
  },
});
添加新表
  1. 在功能库文件夹中创建架构:
// 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(),
});
  1. 在 src/lib/db/client.ts 中导入架构:
import * as itemSchema from "@/lib/feature/schema";

const schema = {
  ...authSchema,
  ...chatSchema,
  ...itemSchema,
};
  1. 生成并运行迁移:
bun run db:generate
bun run db:migrate

参考资料

评论

支持 Markdown