From andrelandgraf-fullstackrecipes
Write type-safe Postgres queries with Drizzle ORM (select/insert/update/delete, relations, new tables). Use when querying or mutating the database or adding a Drizzle table.
How this skill is triggered — by the user, by Claude, or both
Slash command
/andrelandgraf-fullstackrecipes:drizzle-queriesThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Write type-safe Postgres queries with Drizzle ORM.
Write type-safe Postgres queries with Drizzle ORM.
Complete these setup recipes first:
Import db from @/lib/db/client and operators from drizzle-orm. For a single row, .limit(1) then take 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]);
Use .returning() when the inserted row is needed back.
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));
Use db.query.<table> for relations instead of manual joins.
const chatWithMessages = await db.query.chats.findFirst({
where: eq(chats.id, chatId),
with: {
messages: {
orderBy: (messages, { asc }) => [asc(messages.createdAt)],
},
},
});
Co-locate the schema in the feature's library folder, register it on the shared client, then migrate.
// 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
npx claudepluginhub joshuarweaver/cascade-code-general-misc-3 --plugin andrelandgraf-fullstackrecipesDesigns type-safe database schemas and queries using Drizzle ORM, including migrations, relational queries, and serverless integrations.
Provides Drizzle ORM reference for PostgreSQL: pgTable schemas with types/indexes/constraints, typesafe queries/joins/relations, drizzle-kit migrations, sql template, and PostGIS/pg_vector extensions.
Provides type-safe SQL with Drizzle ORM for defining schemas, writing queries, setting relations, and running migrations across PostgreSQL, MySQL, SQLite, Cloudflare D1, and Durable Objects.