Drizzle Orm 标志

Drizzle Orm

社区
ericrisco
drizzle-orm

Use when modeling data or querying with Drizzle ORM in TypeScript — `pgTable` schema in `.ts`, type-safe select/insert/relational queries, `drizzle-kit` migrations. NOT Prisma Client or `schema.prisma` (that is `prisma-orm`), NOT ORM-agnostic migration strategy (that is `db-migrations`), NOT Postgres engine tuning or EXPLAIN (that is `postgresdb`).

概览

发布者ericrisco
代码仓库rsc-harness
技能名称drizzle-orm
星标数
239
复刻数
24
附带文件
3
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 3 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 ericrisco 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Drizzle Orm AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ericrisco/rsc-harness/tree/main/skills/drizzle-orm
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ericrisco/rsc-harness.git /tmp/rsc-harness
mkdir -p .claude/skills
cp -r /tmp/rsc-harness/skills/drizzle-orm .claude/skills/drizzle-orm
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Drizzle Orm,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Drizzle Orm。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Drizzle Orm 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Drizzle ORM — schema as code, type-safe queries, drizzle-kit migrations

Drizzle is the SQL-transparent TypeScript ORM: you declare tables in plain .ts, the query builder emits SQL you can read, and there is no codegen client to regenerate. It runs in edge/serverless runtimes. You own the schema, the queries, and the drizzle-kit workflow here — the database engine, the ORM-agnostic migration strategy, and Prisma live in sibling skills.

Decide first

Three decisions before you write a line. Each branches, so use the table.

DecisionPickWhy
Drizzle vs PrismaDrizzle when you want SQL you can read, no codegen step, edge runtimePrisma's generated client + schema.prisma DSL is the opposite trade — use ../prisma-orm/SKILL.md if that is the ask
Version0.45.x + drizzle-kit@0.31.x for productionnpm latest is drizzle-orm@0.45.2; the 0.45 line has been latest since 2025-12-04 (checked 2026-06-02)
Version1.0.0-rc.x (npm rc tag = 1.0.0-rc.3, 2026-05-18) for a NEW edge-first projectv1 has moved past beta into release candidates with Relations v2 — close to stable, but still pin an exact rc and expect late API churn
Driver entrypointmatch it to your DB/host (see below)Each driver has its own drizzle-orm/<driver> import and its own client

Driver entrypoints (pick one; full matrix + edge caveats in references/relations-and-drivers.md): drizzle-orm/node-postgres, /postgres-js, /neon-http, /libsql (Turso), /planetscale-serverless, /mysql2, /better-sqlite3, /bun-sqlite.

Install & config

bash
npm i drizzle-orm
npm i -D drizzle-kit
npm i postgres            # the driver client — here postgres-js; swap per your DB

drizzle.config.ts — the four keys drizzle-kit reads. The dialect here MUST match your table helper (pgTable ⇒ 'postgresql'), or migrations target the wrong SQL.

ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',          // 'postgresql' | 'mysql' | 'sqlite' | 'turso'
  schema: './src/db/schema.ts',   // where your tables live
  out: './drizzle',               // emitted migration SQL
  dbCredentials: { url: process.env.DATABASE_URL! },
});

package.json scripts — name them once so you never re-type the CLI:

json
{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:migrate": "drizzle-kit migrate",
    "db:push": "drizzle-kit push",
    "db:studio": "drizzle-kit studio"
  }
}

Schema as code

A table is plain TypeScript. Declare columns with the helpers, then derive your row types from the table — never hand-write a parallel interface, it will drift.

ts
import { pgTable, integer, text, timestamp, pgEnum, index } from 'drizzle-orm/pg-core';

export const roleEnum = pgEnum('role', ['admin', 'member']);

export const users = pgTable('users', {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  email: text().notNull().unique(),
  role: roleEnum().notNull().default('member'),
  createdAt: timestamp().notNull().defaultNow(),
}, (t) => [index('users_email_idx').on(t.email)]);

export const posts = pgTable('posts', {
  id: integer().primaryKey().generatedAlwaysAsIdentity(),
  authorId: integer().notNull().references(() => users.id),  // FK
  title: text().notNull(),
});

export type User = typeof users.$inferSelect;       // row as read
export type NewUser = typeof users.$inferInsert;    // row as inserted
  • One schema file per domain, and export every table. drizzle-kit and the relational query builder only see what you pass them — an unexported table is invisible to migrations.
  • Derive types with $inferSelect / $inferInsert. They stay in sync with the column defs for free; a separate interface is one more thing to forget to update.

Connect

drizzle() takes your driver client. Pass { schema } (0.45 / v1-compat) or { relations } (v2, the 1.0 rc line) — without one of them, db.query.* is undefined and relational reads silently break.

ts
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client, { schema });   // schema enables db.query.*

Query

Filter, join, and shape in SQL — not in JavaScript after the fact.

ts
import { eq, and, inArray, desc } from 'drizzle-orm';

// select a column subset, not the whole row
const admins = await db.select({ id: users.id, email: users.email })
  .from(users)
  .where(and(eq(users.role, 'admin'), inArray(users.id, [1, 2, 3])))
  .orderBy(desc(users.createdAt));

// insert + get the row back
const [created] = await db.insert(users)
  .values({ email: 'a@b.com', role: 'member' })
  .returning();

// update / delete take the same operators
await db.update(users).set({ role: 'admin' }).where(eq(users.id, created.id));
await db.delete(posts).where(eq(posts.authorId, created.id));

// transaction — all or nothing
await db.transaction(async (tx) => {
  const [u] = await tx.insert(users).values({ email: 'c@d.com' }).returning();
  await tx.insert(posts).values({ authorId: u.id, title: 'hello' });
});

Relational read (nested objects) needs { schema }/{ relations } on the connection AND a with:

ts
const withPosts = await db.query.users.findMany({
  where: (u, { eq }) => eq(u.role, 'admin'),
  with: { posts: true },          // <- the relation; omit it and you get no posts
});

For conditional builders use $dynamic(); for hot paths prepare() once and reuse.

ts
const q = db.select().from(users).$dynamic();
const rows = await (role ? q.where(eq(users.role, role)) : q);

Bad → Good — the classic foot-gun:

ts
// Bad: pull every row, filter in JS — full table scan, no index, ships rows you discard
const all = await db.query.users.findMany();
const admins = all.filter((u) => u.role === 'admin');

// Good: filter in the query — the DB uses the index and returns only what you need
const admins = await db.query.users.findMany({ where: (u, { eq }) => eq(u.role, 'admin') });

Relations

Relations let with hydrate nested objects. Two flavors — do not mix them in one project.

LineDefineConnectRead
0.45 / v1-compatrelations(users, ({ many }) => ({ posts: many(posts) }))drizzle(client, { schema })db.query.users.findMany({ with: { posts: true } })
v2 (1.0 rc)defineRelations(schema, (r) => ({ users: { posts: r.many.posts() } }))drizzle(client, { relations })db.query.… (RQBv2); db._query.… keeps v1 syntax for back-compat

Decision line: use the relational query (db.query + with) for nested reads of related records; drop to a manual .leftJoin() for flat projections, aggregates, or GROUP BY — relational queries return trees, joins return rows. Full v1↔v2 migration walkthrough in references/relations-and-drivers.md.

Migrations

bash
npm run db:generate   # diff schema.ts vs ./drizzle, emit a new .sql migration
# READ the emitted SQL in ./drizzle — confirm it does what you intended
npm run db:migrate    # apply pending migrations
  • generate → review the SQL → migrate is the production path. The emitted SQL is the contract; eyeball it before applying so a rename does not silently become a drop+add.
  • push is for throwaway prototyping only. It applies schema.ts straight to the DB with no migration file — fine for a scratch branch, never for an environment you cannot recreate.
  • Never hand-edit an applied migration; write a new one. The migration journal tracks what ran; editing history desyncs every other environment.
  • Recent drizzle-kit adds migration-conflict / commutativity detection (it checks whether open migration branches merge safely, with refined index/table footprint checks); --ignore-conflicts preserves open leaf parents when you intend to keep branches. node:sqlite is auto-detected for migrate and Studio.

Inspect data with npm run db:studio (Drizzle Studio GUI); pull an existing DB into a schema with drizzle-kit pull.

Anti-patterns

Anti-patternWhy it bitesDo instead
push against a real/shared DBno migration record; irreproducible, unreviewablegenerate → review → migrate
Hand-editing an applied migrationdesyncs the journal across environmentswrite a new migration
findMany() then .filter() in JSfull scan, no index, ships discarded rowsfilter in where
db.query.* with no { schema }/{ relations } on drizzle()db.query is undefined; relations never loadpass { schema } (v1) or { relations } (v2)
with omitted but relation expectedreturns parent only, no nested rowsadd with: { posts: true }
dialect in config ≠ table helpermigrations target the wrong SQL dialectpgTable⇒'postgresql', mysqlTable⇒'mysql', etc.
Mixing relations() and defineRelationsthe two relation systems conflictpick one line per project
select() returning every columnover-fetches, fragile to schema growthselect({ id, email }) subset
Not awaiting a query buildera builder is a thenable, not a promise — un-awaited it never runsawait db.select()…
Hand-written interface mirroring a tabledrifts from the column defstypeof t.$inferSelect/$inferInsert

Verify

Run the static lint on any generated Drizzle file (no DB connection):

bash
scripts/verify.sh src/db/schema.ts drizzle.config.ts

It checks a drizzle() call exists, the table helper matches the configured dialect, the config carries dialect/schema/out, that any db.query usage has { schema }/{ relations } passed to drizzle(), and bans Prisma-isms (schema.prisma, PrismaClient, prisma generate) that mean the wrong ORM leaked in.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Drizzle Orm AI 技能有什么作用?

Use when modeling data or querying with Drizzle ORM in TypeScript — `pgTable` schema in `.ts`, type-safe select/insert/relational queries, `drizzle-kit` migrations. NOT Prisma Client or `schema.prisma` (that is `prisma-orm`), NOT ORM-agnostic migration strategy (that is `db-migrations`), NOT Postgres engine tuning or EXPLAIN (that is `postgresdb`).

为什么在 TypingMind 中使用 Drizzle Orm?

因为您只需安装一次,就能搭配任何模型使用。Drizzle Orm 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Drizzle Orm?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ericrisco/rsc-harness/tree/main/skills/drizzle-orm。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Drizzle Orm?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Drizzle Orm 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Drizzle Orm 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Drizzle Orm AI 技能免费吗?

是的。该技能源自 ericrisco 在 GitHub 上以 MIT 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇