Logo Nodejs Drizzle

Nodejs Drizzle

Cộng đồng
j4flmao
nodejs-drizzle

Use this skill when working with Drizzle ORM — schema definition, SQL-like queries, migrations, relations, and edge deployment. This skill enforces: schema-first design, explicit SQL patterns, drizzle-kit for migrations, relational query builder, and connection management. Requires drizzle-orm and drizzle-kit. Do NOT use for: Prisma, TypeORM, Mongoose, or non-Drizzle ORM frameworks.

Tổng quan

Nhà phát hànhj4flmao
Kho mãagent-skills
Tên kỹ năngnodejs-drizzle
Sao
41
Bản fork
6
Tệp đi kèm
6
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 6 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được j4flmao công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Nodejs Drizzle trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/nodejs/drizzle
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/nodejs/drizzle .claude/skills/nodejs-drizzle
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Nodejs Drizzle trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Nodejs Drizzle ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Nodejs Drizzle không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Drizzle ORM

Purpose

Design database schemas, write SQL-like queries, manage migrations, define relations, and optimize Drizzle ORM for production and edge deployment.

Agent Protocol

Trigger

User request includes: drizzle, drizzle orm, drizzle schema, drizzle migrate, drizzle query, drizzle relation, drizzle edge, drizzle neon, drizzle planetscale.

Input Context

  • Database (PostgreSQL, MySQL, SQLite, Turso)
  • Drizzle version (0.30+)
  • Runtime (Node.js, Bun, Cloudflare Workers, Neon)
  • Deployment (serverless, edge, traditional)

Output Artifact

Schema definition, query examples, migration setup, relation config, connection management.

Response Format

Produce artifact directly. No preamble, no postamble, no explanations.

Completion Criteria

  • Schema defined with drizzle-orm/pg-core or mysql-core
  • Relations defined with drizzle-orm relations
  • Migrations generated and applied with drizzle-kit
  • Queries use prepared statements for production
  • Connection configured for target environment (Node, serverless, edge)

Max Response Length

4096 tokens

Architecture Decision Trees

Drizzle vs Prisma

CriterionDrizzle ORMPrisma
PerformanceFast (thin SQL wrapper)Moderate (mapped layer)
Bundle sizeTiny (tree-shakeable)Large (generated client)
Type safetyFull (inferred from schema)Full (generated types)
SQL controlDirect SQL with typesPrisma Client abstractions
MigrationsDrizzle KitPrisma Migrate
Edge supportFirst-class (Neon, Turso, PlanetScale)Via adapter
RelationsRelations module (INSERT-friendly)include/select

Decision: Performance + SQL control + edge → Drizzle. Rich ORM features + auto-complete → Prisma.

Database Driver Selection

DatabaseDriverDrizzle PackageBest For
PostgreSQLpg or @neondatabase/serverlessdrizzle-orm/pg-coreFull-featured RDBMS
MySQLmysql2drizzle-orm/mysql-corePlanetScale, traditional MySQL
SQLitebetter-sqlite3 or @libsql/clientdrizzle-orm/sqlite-coreTurso, local, edge
PostgreSQL (serverless)@vercel/postgresdrizzle-orm/vercel-postgresVercel edge functions

Workflow

Step 1: Schema Definition

typescript
// src/db/schema/users.ts
import { pgTable, uuid, varchar, boolean, timestamp, uniqueIndex, index } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';

export const users = pgTable('users', {
  id: uuid('id').defaultRandom().primaryKey(),
  email: varchar('email', { length: 255 }).notNull(),
  name: varchar('name', { length: 100 }).notNull(),
  role: varchar('role', { length: 20 }).$type<'admin' | 'user'>().default('user'),
  active: boolean('active').default(true),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  emailIdx: uniqueIndex('users_email_idx').on(table.email),
  activeIdx: index('users_active_idx').on(table.active),
}));

// src/db/schema/posts.ts
import { pgTable, uuid, varchar, text, boolean, timestamp, index } from 'drizzle-orm/pg-core';
import { users } from './users';

export const posts = pgTable('posts', {
  id: uuid('id').defaultRandom().primaryKey(),
  title: varchar('title', { length: 255 }).notNull(),
  content: text('content'),
  published: boolean('published').default(false),
  authorId: uuid('author_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull().$onUpdate(() => new Date()),
}, (table) => ({
  authorIdx: index('posts_author_idx').on(table.authorId),
  publishedIdx: index('posts_published_idx').on(table.authorId, table.published),
}));

Step 2: Relations

typescript
// src/db/schema/relations.ts
import { relations } from 'drizzle-orm';
import { users } from './users';
import { posts } from './posts';

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

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

Step 3: Connection and Query

typescript
// src/db/index.ts
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 });

// src/repositories/user.repository.ts
import { db } from '../db';
import { users } from '../db/schema/users';
import { eq, and, desc, count, ilike } from 'drizzle-orm';

export async function findUserById(id: string) {
  const result = await db
    .select({
      id: users.id,
      name: users.name,
      email: users.email,
      role: users.role,
    })
    .from(users)
    .where(eq(users.id, id))
    .limit(1);
  return result[0] || null;
}

export async function findUserWithPosts(id: string) {
  return db.query.users.findFirst({
    where: eq(users.id, id),
    with: {
      posts: {
        where: eq(posts.published, true),
        orderBy: [desc(posts.createdAt)],
        limit: 10,
      },
    },
  });
}

export async function findUsers(page: number, limit: number) {
  const [data, total] = await Promise.all([
    db
      .select()
      .from(users)
      .offset((page - 1) * limit)
      .limit(limit)
      .orderBy(desc(users.createdAt)),
    db.select({ count: count() }).from(users),
  ]);
  return { data, total: total[0].count, page };
}

export async function createUser(data: { email: string; name: string }) {
  const result = await db.insert(users).values(data).returning();
  return result[0];
}

export async function updateUser(id: string, data: Partial<{ name: string; email: string }>) {
  const result = await db
    .update(users)
    .set(data)
    .where(eq(users.id, id))
    .returning();
  return result[0];
}

export async function deleteUser(id: string) {
  await db.delete(users).where(eq(users.id, id));
}

export async function searchUsers(query: string) {
  return db
    .select()
    .from(users)
    .where(ilike(users.name, `%${query}%`))
    .limit(20);
}

Step 4: Prepared Statements

typescript
// src/db/prepared.ts
import { db } from './index';
import { users } from './schema/users';
import { eq } from 'drizzle-orm';

// Prepared statements for hot paths (cached query plans)
export const getUserById = db.select({
  id: users.id,
  name: users.name,
  email: users.email,
}).from(users).where(eq(users.id, sql.placeholder('id'))).prepare('get_user_by_id');

// Usage
const user = await getUserById.execute({ id: 'some-uuid' });

Step 5: Migrations with Drizzle Kit

bash
# Generate migration
npx drizzle-kit generate --name add_user_profile

# Apply migration
npx drizzle-kit migrate

# Push schema (dev only)
npx drizzle-kit push

# Check schema diff
npx drizzle-kit check

# Drizzle Kit config
typescript
// drizzle.config.ts
import type { Config } from 'drizzle-kit';

export default {
  schema: './src/db/schema/*.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
} satisfies Config;

Step 6: Edge/Serverless Connection

typescript
// src/db/edge.ts — Neon serverless
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
import * as schema from './schema';

const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql, { schema });

// src/db/turso.ts — Turso (SQLite edge)
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';

const client = createClient({ url: process.env.TURSO_DB_URL!, authToken: process.env.TURSO_AUTH_TOKEN! });
export const db = drizzle(client, { schema });

Implementation Patterns

Pattern: Batch Insert

typescript
export async function createUsers(data: { email: string; name: string }[]) {
  return db.insert(users).values(data).returning();
}

Pattern: Raw SQL with Type Safety

typescript
import { sql } from 'drizzle-orm';

export async function getActiveUsersCount() {
  const result = await db.execute(
    sql`SELECT COUNT(*) as count FROM users WHERE active = true`
  );
  return result.rows[0].count;
}

Production Considerations

Connection Management

typescript
// Node.js (connection pooling)
const pool = new Pool({ max: 20, idleTimeoutMillis: 30000 });

// Graceful shutdown
process.on('SIGTERM', async () => {
  await pool.end();
  process.exit(0);
});

Performance

  • Prepared statements for hot query paths (cached execution plans)
  • Use db.query.* with with for relation loading (Drizzle batches these)
  • Partial<Model> for updates instead of full object
  • returning() for INSERT/UPDATE/DELETE to avoid separate SELECT
  • Use drizzle-orm/zod to generate Zod schemas from Drizzle schemas for validation

Anti-Patterns

Anti-PatternWhyFix
Missing .prepare() on hot queriesFull query parse each callUse .prepare() for frequent queries
select * in productionOverfetching, type safety lossExplicit column selection
Direct pool in edge runtimeConnection leak, timeoutUse Neon HTTP or Turso HTTP driver
N+1 via manual relation queriesSequential DB callsUse db.query.*.findFirst({with})
No $onUpdate on timestampsStale updated_atAlways add $onUpdate(() => new Date())

Security Considerations

  • Drizzle uses parameterized queries by default — SQL injection resistant
  • Raw sql template tags are safe (parameterized), sql.raw() is not — avoid it
  • Validate all inputs before passing to Drizzle queries (Zod at API boundary)
  • Connection strings from environment variables — never hardcoded
  • Row Level Security (RLS) for multi-tenant schemas

Testing Strategies

typescript
import { test, expect, beforeAll, afterAll } from 'vitest';
import { Pool } from 'pg';
import { drizzle } from 'drizzle-orm/node-postgres';
import * as schema from '../src/db/schema';

const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL });
const db = drizzle(pool, { schema });

beforeAll(async () => {
  await db.execute(sql`TRUNCATE TABLE users CASCADE`);
});

afterAll(async () => {
  await pool.end();
});

test('create and find user', async () => {
  const [user] = await db.insert(users).values({
    email: 'test@test.com',
    name: 'Test',
  }).returning();
  expect(user.email).toBe('test@test.com');

  const found = await db.query.users.findFirst({
    where: eq(users.id, user.id),
  });
  expect(found).toBeDefined();
});

Use TEST_DATABASE_URL for test isolation. Run tests with --pool=forks for parallelism. Use drizzle-kit push to set up test schema.

Rules

  • Schema defined in TypeScript — one file per logical domain (users, posts, orders).
  • Relations defined separately in relations.ts for each domain.
  • Drizzle Kit for all migrations — never manual SQL schema changes.
  • db.select({ columns }).from(table).where(condition) over select *.
  • db.query.table.findFirst/findMany({ with, where }) for relation queries.
  • Prepared statements via .prepare('name') for hot paths.
  • Edge databases use HTTP drivers (Neon, Turso), not TCP.
  • All timestamp columns have $onUpdate for mutation tracking.

References

  • references/drizzle-advanced.md — Advanced Drizzle Patterns
  • references/drizzle-edge-deployment.md — Edge and Serverless Deployment
  • references/drizzle-relations.md — Relation Patterns
  • references/migration-patterns.md — Migration Strategies
  • references/query-optimization.md — Query Optimization
  • references/schema-types.md — Schema Design and Types

Handoff

Hand off to backend/nodejs/prisma/SKILL.md for Prisma ORM or backend/nodejs/patterns/SKILL.md for advanced Node patterns.

Implementation Patterns

Pattern: CRUD Repository with Drizzle

typescript
import { pgTable, serial, text, timestamp, uuid } from 'drizzle-orm/pg-core';
import { eq } from 'drizzle-orm';
import { db } from './db';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  uuid: uuid('uuid').defaultRandom().notNull(),
  email: text('email').notNull().unique(),
  name: text('name').notNull(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
});

export class UserRepository {
  async findById(id: number) {
    return db.select().from(users).where(eq(users.id, id)).limit(1);
  }

  async findByEmail(email: string) {
    return db.select().from(users).where(eq(users.email, email)).limit(1);
  }

  async create(data: { email: string; name: string }) {
    return db.insert(users).values(data).returning();
  }

  async update(id: number, data: Partial<{ email: string; name: string }>) {
    return db.update(users).set(data).where(eq(users.id, id)).returning();
  }

  async delete(id: number) {
    return db.delete(users).where(eq(users.id, id)).returning();
  }
}

Pattern: Transaction with Relation Queries

typescript
import { drizzle } from 'drizzle-orm/node-postgres';
import { sql } from 'drizzle-orm';

async function createOrderWithItems(orderData: OrderInput, items: ItemInput[]) {
  return await db.transaction(async (tx) => {
    const [order] = await tx.insert(orders).values(orderData).returning();

    const orderItems = items.map(item => ({
      ...item,
      orderId: order.id,
    }));

    const inserted = await tx.insert(orderItems).values(orderItems).returning();

    await tx.update(inventory)
      .set({ quantity: sql`quantity - ${items.length}` })
      .where(eq(inventory.productId, orderData.productId));

    return { order, items: inserted };
  });
}

Production Considerations

  • Connection pooling: use pg pool with Drizzle. Max 20 connections per instance.
  • Migration strategy: drizzle-kit push for dev. drizzle-kit migrate for prod. Always version-controlled.
  • Query logging: Drizzle logger in dev only. Structured logging with Pino in prod.
  • Prepared statements: Drizzle uses them by default. Cache hit ratio improves latency.
  • Connection timeout: 30s idle. 60s statement timeout. Kill hung queries.
  • Connection validation: test query on checkout. Reconnect on failure.
  • Metrics: track query count, duration, rows returned per request.
  • Migrations: generate SQL files. Review in PR. Apply via CI/CD pipeline.

Anti-Patterns

Anti-PatternWhy It HurtsFix
Raw SQL strings everywhereNo type safety. SQL injection risk.Use Drizzle query builder. Raw only when absolutely needed.
Over-fetching in relationsSelect * with joins brings unnecessary columns.Explicit select with only needed columns.
N+1 in relational queriesLoop querying related entities.Use Drizzle relations with with or batch loading.
Missing indexes on foreign keysSlow JOINs on large tables.Index all FK columns. Use EXPLAIN ANALYZE.
Migrations without reviewSchema drift. Production issues.PR review for all migrations. Test on staging first.

Performance Optimization

  • Use partial indexes for filtered queries (WHERE status = 'active').
  • EXPLAIN ANALYZE on all slow queries. Look for seq scans on large tables.
  • Batch inserts with db.insert(table).values(rows) for bulk operations.
  • Read replicas for reporting queries. Separate read/write connections.
  • JSON columns for flexible schema. Index with GIN for query performance.
  • Materialized views for dashboard queries. Refresh on schedule.
  • Use limit + offset for pagination. Keyset pagination for large datasets.
  • Prepared statement caching reduces parse overhead for repeated queries.

Security Considerations

  • SQL injection: Drizzle parameterizes all queries. Never use sql template tag with user input.
  • Input validation: Zod schemas before passing to Drizzle. Validate types and constraints.
  • Connection encryption: ssl: true for production. Reject unauthorized certs.
  • Credential management: environment variables or vault. Never in code or config files.
  • Row-level security: enable via sql template with tenant context. Enforce per query.
  • Audit logging: trigger-based tracking for sensitive tables. Log all mutations.
  • Schema access: read-only user for reports. Separate migration user. Least privilege.

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Nodejs Drizzle làm được gì?

Use this skill when working with Drizzle ORM — schema definition, SQL-like queries, migrations, relations, and edge deployment. This skill enforces: schema-first design, explicit SQL patterns, drizzle-kit for migrations, relational query builder, and connection management. Requires drizzle-orm and drizzle-kit. Do NOT use for: Prisma, TypeORM, Mongoose, or non-Drizzle ORM frameworks.

Vì sao nên dùng Nodejs Drizzle trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Nodejs Drizzle là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Nodejs Drizzle trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/j4flmao/agent-skills/tree/main/skills/backend/nodejs/drizzle. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Nodejs Drizzle?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Nodejs Drizzle với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Nodejs Drizzle với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Nodejs Drizzle có miễn phí không?

Có. Kỹ năng này được j4flmao phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇