Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

drizzle-ormDrizzle ORM

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

499

周安装

21

GitHub Stars

公开资料未说明

下载量

175
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:drizzle-orm(Drizzle ORM)
来源仓库:https://github.com/constructive-io/constructive-skills
仓库路径:skills/drizzle-orm
安装命令:
npx skills add https://github.com/constructive-io/constructive-skills --skill drizzle-orm
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/constructive-io/constructive-skills --skill drizzle-orm

简介

用于 PostgreSQL 数据库的模式设计与类型安全查询开发。

  • 支持 Drizzle ORM 集成,提供 schema 定义、查询构建和测试工具链。
  • 适用于新项目数据库设计或现有项目的类型增强改造。
  • 需明确数据库连接环境和目标表结构,谨慎执行写入类操作。
  • drizzle-orm 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Drizzle ORM Patterns

Design PostgreSQL schemas and write type-safe queries with Drizzle ORM. This skill covers schema design patterns, query building, and integration with the Constructive ecosystem.

When to Apply

Use this skill when:

  • Designing database schemas with Drizzle
  • Writing type-safe database queries
  • Setting up Drizzle ORM in a project
  • Integrating Drizzle with pgsql-test or drizzle-orm-test

Installation

pnpm add drizzle-orm
pnpm add -D drizzle-kit

Schema Design

Basic Table Definition

import { pgTable, uuid, text, timestamp, boolean, integer } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  name: text('name'),
  isActive: boolean('is_active').default(true),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow()
});

Foreign Key Relations

import { pgTable, uuid, text, timestamp } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique()
});

export const posts = pgTable('posts', {
  id: uuid('id').primaryKey().defaultRandom(),
  title: text('title').notNull(),
  content: text('content'),
  authorId: uuid('author_id').references(() => users.id).notNull(),
  createdAt: timestamp('created_at').defaultNow()
});

export const comments = pgTable('comments', {
  id: uuid('id').primaryKey().defaultRandom(),
  content: text('content').notNull(),
  postId: uuid('post_id').references(() => posts.id).notNull(),
  authorId: uuid('author_id').references(() => users.id).notNull()
});

Indexes

import { pgTable, uuid, text, index, uniqueIndex } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull(),
  organizationId: uuid('organization_id').notNull()
}, (table) => [
  uniqueIndex('users_email_idx').on(table.email),
  index('users_org_idx').on(table.organizationId)
]);

Composite Primary Keys

import { pgTable, uuid, primaryKey } from 'drizzle-orm/pg-core';

export const userRoles = pgTable('user_roles', {
  userId: uuid('user_id').references(() => users.id).notNull(),
  roleId: uuid('role_id').references(() => roles.id).notNull()
}, (table) => [
  primaryKey({ columns: [table.userId, table.roleId] })
]);

Enums

import { pgTable, uuid, pgEnum } from 'drizzle-orm/pg-core';

export const statusEnum = pgEnum('status', ['pending', 'active', 'archived']);

export const projects = pgTable('projects', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: text('name').notNull(),
  status: statusEnum('status').default('pending')
});

JSON Columns

import { pgTable, uuid, jsonb } from 'drizzle-orm/pg-core';

export const settings = pgTable('settings', {
  id: uuid('id').primaryKey().defaultRandom(),
  userId: uuid('user_id').references(() => users.id).notNull(),
  preferences: jsonb('preferences').$type<{
    theme: 'light' | 'dark';
    notifications: boolean;
  }>()
});

Query Patterns

Setup Client

import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL
});

export const db = drizzle(pool, { schema });

Select Queries

import { eq, and, or, like, gt, lt, isNull, inArray } from 'drizzle-orm';
import { users, posts } from './schema';

// Select all
const allUsers = await db.select().from(users);

// Select with where
const activeUsers = await db
  .select()
  .from(users)
  .where(eq(users.isActive, true));

// Select specific columns
const userEmails = await db
  .select({ email: users.email, name: users.name })
  .from(users);

// Multiple conditions
const filteredUsers = await db
  .select()
  .from(users)
  .where(and(
    eq(users.isActive, true),
    like(users.email, '%@example.com')
  ));

// OR conditions
const result = await db
  .select()
  .from(users)
  .where(or(
    eq(users.name, 'Alice'),
    eq(users.name, 'Bob')
  ));

// IN clause
const specificUsers = await db
  .select()
  .from(users)
  .where(inArray(users.id, ['id1', 'id2', 'id3']));

// NULL checks
const usersWithoutName = await db
  .select()
  .from(users)
  .where(isNull(users.name));

Insert Queries

// Single insert
const [newUser] = await db
  .insert(users)
  .values({
    email: 'alice@example.com',
    name: 'Alice'
  })
  .returning();

// Multiple insert
const newUsers = await db
  .insert(users)
  .values([
    { email: 'alice@example.com', name: 'Alice' },
    { email: 'bob@example.com', name: 'Bob' }
  ])
  .returning();

// Insert with conflict handling
await db
  .insert(users)
  .values({ email: 'alice@example.com', name: 'Alice' })
  .onConflictDoNothing();

// Upsert
await db
  .insert(users)
  .values({ email: 'alice@example.com', name: 'Alice' })
  .onConflictDoUpdate({
    target: users.email,
    set: { name: 'Alice Updated' }
  });

Update Queries

// Update with where
const [updated] = await db
  .update(users)
  .set({ name: 'Alice Smith' })
  .where(eq(users.id, userId))
  .returning();

// Update multiple fields
await db
  .update(users)
  .set({
    name: 'Alice Smith',
    updatedAt: new Date()
  })
  .where(eq(users.id, userId));

Delete Queries

// Delete with where
await db
  .delete(users)
  .where(eq(users.id, userId));

// Delete with returning
const [deleted] = await db
  .delete(users)
  .where(eq(users.id, userId))
  .returning();

Joins

// Inner join
const postsWithAuthors = await db
  .select({
    postTitle: posts.title,
    authorName: users.name
  })
  .from(posts)
  .innerJoin(users, eq(posts.authorId, users.id));

// Left join
const usersWithPosts = await db
  .select({
    userName: users.name,
    postTitle: posts.title
  })
  .from(users)
  .leftJoin(posts, eq(users.id, posts.authorId));

Relational Queries

With schema relations defined:

import { relations } from 'drizzle-orm';

export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts)
}));

export const postsRelations = relations(posts, ({ one, many }) => ({
  author: one(users, {
    fields: [posts.authorId],
    references: [users.id]
  }),
  comments: many(comments)
}));

Query with relations:

// Fetch users with their posts
const usersWithPosts = await db.query.users.findMany({
  with: {
    posts: true
  }
});

// Nested relations
const usersWithPostsAndComments = await db.query.users.findMany({
  with: {
    posts: {
      with: {
        comments: true
      }
    }
  }
});

// Selective columns with relations
const result = await db.query.users.findMany({
  columns: {
    id: true,
    name: true
  },
  with: {
    posts: {
      columns: {
        title: true
      }
    }
  }
});

Aggregations

import { count, sum, avg, max, min } from 'drizzle-orm';

// Count
const [{ total }] = await db
  .select({ total: count() })
  .from(users);

// Count with condition
const [{ activeCount }] = await db
  .select({ activeCount: count() })
  .from(users)
  .where(eq(users.isActive, true));

// Group by
const postCounts = await db
  .select({
    authorId: posts.authorId,
    postCount: count()
  })
  .from(posts)
  .groupBy(posts.authorId);

Ordering and Pagination

import { desc, asc } from 'drizzle-orm';

// Order by
const sortedUsers = await db
  .select()
  .from(users)
  .orderBy(desc(users.createdAt));

// Multiple order columns
const sorted = await db
  .select()
  .from(users)
  .orderBy(asc(users.name), desc(users.createdAt));

// Pagination
const page = await db
  .select()
  .from(users)
  .limit(10)
  .offset(20);

Transactions

await db.transaction(async (tx) => {
  const [user] = await tx
    .insert(users)
    .values({ email: 'alice@example.com' })
    .returning();

  await tx
    .insert(posts)
    .values({
      title: 'First Post',
      authorId: user.id
    });
});

Integration with pgsql-test

import { getConnections, PgTestClient } from 'drizzle-orm-test';
import { drizzle } from 'drizzle-orm/node-postgres';
import * as schema from './schema';

let pg: PgTestClient;
let db: ReturnType<typeof drizzle>;
let teardown: () => Promise<void>;

beforeAll(async () => {
  ({ pg, teardown } = await getConnections());
  db = drizzle(pg.client, { schema });
});

afterAll(async () => {
  await teardown();
});

beforeEach(async () => {
  await pg.beforeEach();
});

afterEach(async () => {
  await pg.afterEach();
});

it('creates a user', async () => {
  const [user] = await db
    .insert(schema.users)
    .values({ email: 'test@example.com' })
    .returning();

  expect(user.email).toBe('test@example.com');
});

Schema Organization

For larger projects, organize schemas by domain:

src/
  db/
    schema/
      index.ts        # Re-exports all schemas
      users.ts        # User-related tables
      posts.ts        # Post-related tables
      relations.ts    # All relations
    client.ts         # Drizzle client setup
// src/db/schema/index.ts
export * from './users';
export * from './posts';
export * from './relations';

Best Practices

  1. Use UUID primary keys: uuid('id').primaryKey().defaultRandom()
  2. Add timestamps: Include createdAt and updatedAt on most tables
  3. Define relations: Enable relational queries with relations()
  4. Type JSON columns: Use .$type<T>() for type-safe JSON
  5. Index foreign keys: Add indexes on frequently queried foreign keys
  6. Use transactions: Wrap related operations in transactions
  7. Return inserted/updated rows: Use .returning() to get results

References

  • Related skill: drizzle-orm-test for testing with Drizzle
  • Related skill: pgsql-test-snapshot for snapshot testing
  • Related skill: pgsql-test-rls for RLS testing with Drizzle

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.95%
按下载量换算63

Claude

30.52%
按下载量换算53

Cursor

19.78%
按下载量换算35

Gemini CLI

8.69%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills