drizzle-conventions
ACTIVATE when defining database schemas, writing queries, creating migrations, or implementing repositories with Drizzle ORM. ACTIVATE for 'Drizzle', 'pgTable', 'drizzle-kit', 'db.query', 'db.select', '$inferSelect', 'migration'. Covers: schema definition with pgTable, relations, type inference ($inferSelect/$inferInsert), Query API vs Select API vs raw SQL decision tree, repository pattern with toDomain/toPersistence, migration workflow (always drizzle-kit generate first, never manual journal). DO NOT use for: Doctrine/PHP queries (see php-sql-conventions), general SQL formatting.
- License 许可
- MIT
- 最近更新
- 2026-10-13
- Stars
- ★ 9
- Forks
- 2
01 前言 Front Matter
- name
- drizzle-conventions
- description
- ACTIVATE when defining database schemas, writing queries, creating migrations, or implementing repositories with Drizzle ORM. ACTIVATE for 'Drizzle', 'pgTable', 'drizzle-kit', 'db.query', 'db.select', '$inferSelect', 'migration'. Covers: schema definition with pgTable, relations, type inference ($inferSelect/$inferInsert), Query API vs Select API vs raw SQL decision tree, repository pattern with toDomain/toPersistence, migration workflow (always drizzle-kit generate first, never manual journal). DO NOT use for: Doctrine/PHP queries (see php-sql-conventions), general SQL formatting.
03 SKILL.md 正文
Drizzle Conventions
Schema Definition
Define tables with pgTable() and typed columns:
// src/infrastructure/persistence/schema/tenant.schema.ts
import { pgTable, uuid, varchar, timestamp, boolean } from 'drizzle-orm/pg-core';
export const tenants = pgTable('tenants', {
id: uuid('id').primaryKey().defaultRandom(),
email: varchar('email', { length: 255 }).notNull().unique(),
firstName: varchar('first_name', { length: 100 }).notNull(),
lastName: varchar('last_name', { length: 100 }).notNull(),
isActive: boolean('is_active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
Relations (Declared Separately)
// src/infrastructure/persistence/schema/relations.ts
import { relations } from 'drizzle-orm';
import { tenants } from './tenant.schema';
import { leases } from './lease.schema';
export const tenantsRelations = relations(tenants, ({ many }) => ({
leases: many(leases),
}));
export const leasesRelations = relations(leases, ({ one }) => ({
tenant: one(tenants, {
fields: [leases.tenantId],
references: [tenants.id],
}),
}));
Type Inference
Use $inferSelect and $inferInsert for type safety:
import { tenants } from './schema/tenant.schema';
// Inferred types from schema
type Tenant = typeof tenants.$inferSelect; // SELECT result type
type NewTenant = typeof tenants.$inferInsert; // INSERT input type
Query API vs Select API vs Raw SQL
Drizzle offers three abstraction levels. Prefer the highest level possible to maximize type safety and refactoring protection.
Query API (preferred) — db.query.*
Type-safe with automatic relations. The return is fully typed, including nested objects:
// ✅ PREFERRED - Type-safe, auto-joined relations, refactoring-safe
const tenantWithLeases = await db.query.tenants.findFirst({
where: eq(tenants.id, tenantId),
with: {
leases: true, // JOIN generated automatically, returns Tenant & { leases: Lease[] }
},
});
Select API — db.select().from()
For queries without relations or complex cases (aggregations, subqueries):
// ✅ CORRECT - Type-safe, but no declarative relations
const activeTenants = await db
.select()
.from(tenants)
.where(eq(tenants.isActive, true));
// Aggregations
const counts = await db
.select({ count: sql<number>`count(*)` })
.from(tenants)
.groupBy(tenants.isActive);
Raw SQL — sql template tag (last resort)
No return typing, no refactoring protection. Only for cases Drizzle does not cover (CTEs, window functions, very specific queries):
import { sql } from 'drizzle-orm';
// ✅ CORRECT - Parameterized via template tag
const result = await db.execute(
sql`SELECT * FROM tenants WHERE email = ${email}`
);
// ❌ AVOID - String interpolation (SQL injection risk)
const result = await db.execute(
`SELECT * FROM tenants WHERE email = '${email}'`
);
Decision Tree
Need nested relations?
├─ YES → Query API (db.query.*.findFirst/findMany)
│
└─ NO → Simple query or aggregation?
├─ YES → Select API (db.select().from())
└─ NO → CTE / window / exotic SQL?
└─ Raw SQL (sql`...`) as last resort
Insert / Update / Delete
// Insert
const [newTenant] = await db
.insert(tenants)
.values({ email, firstName, lastName })
.returning();
// Update
await db
.update(tenants)
.set({ isActive: false, updatedAt: new Date() })
.where(eq(tenants.id, tenantId));
// Delete
await db
.delete(tenants)
.where(eq(tenants.id, tenantId));
Repository Pattern
// domain/port/tenant-repository.ts (interface)
export interface TenantRepository {
findById(id: TenantId): Promise<Tenant | null>;
findByEmail(email: string): Promise<Tenant | null>;
save(tenant: Tenant): Promise<Tenant>;
}
export const TENANT_REPOSITORY = Symbol('TenantRepository');
// infrastructure/persistence/drizzle-tenant-repository.ts
@Injectable()
export class DrizzleTenantRepository implements TenantRepository {
constructor(@Inject('DRIZZLE') private readonly db: DrizzleDatabase) {}
async findById(id: TenantId): Promise<Tenant | null> {
const result = await this.db.query.tenants.findFirst({
where: eq(tenants.id, id),
});
return result ? this.toDomain(result) : null;
}
async save(tenant: Tenant): Promise<Tenant> {
const [row] = await this.db
.insert(tenants)
.values(this.toPersistence(tenant))
.onConflictDoUpdate({
target: tenants.id,
set: this.toPersistence(tenant),
})
.returning();
return this.toDomain(row);
}
private toDomain(row: typeof tenants.$inferSelect): Tenant { ... }
private toPersistence(tenant: Tenant): typeof tenants.$inferInsert { ... }
}
See also:
nest-ddd-conventionsfor the ports & adapters pattern.
Migrations
IMPORTANT: Always start with drizzle-kit generate to produce the 3 artifacts (SQL, journal entry, snapshot). Never manually write the journal (_journal.json) or snapshots — this causes desynchronizations: inconsistent timestamps, missing snapshots, silently ignored migrations. However, the generated SQL can be modified after generation (adding indexes, syntax cleanup, etc.).
# 1. Modify the schema (.schema.ts)
# 2. Generate the migration (produces SQL + snapshot + journal entry)
pnpm drizzle-kit generate
# 3. (Optional) Improve the generated SQL (indexes, constraints, etc.)
# 4. Apply migrations
pnpm drizzle-kit migrate
# Open Drizzle Studio (DB browser)
pnpm drizzle-kit studio
Quick Reference
| Rule | Convention |
|---|---|
| Schema | pgTable() with typed columns |
| Relations | Declared separately from tables |
| Type inference | $inferSelect / $inferInsert |
| Queries with relations | Query API (db.query.*) — preferred |
| Simple queries / aggregations | Select API (db.select().from()) |
| Raw SQL | sql template tag — last resort |
| Repository | Domain interface + Drizzle implementation |
| Mapping | toDomain() / toPersistence() in repository |
| Migrations | drizzle-kit generate + drizzle-kit migrate — never manual journal/snapshots, SQL editable |
04 同仓库更多 Skills
vitest-test-conventions
ACTIVATE when writing Vitest tests, creating test files, using vi.fn()/vi.mock()/vi.spyOn(), or test factories. ACTIVATE for 'Vitest', 'it.each', 'NestJS testing module', 'supertest', 'vi.fn', 'vi.mock', 'spyOn'. Provides Vitest/NestJS-specific testing patterns; cross-language testing principles (DAMP, AAA, spy over mock, what NOT to test) live in craft:testing-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), TDD workflow/iterations (see vitest:vitest-tdd-workflow), PHP/PHPUnit tests (see phpunit:php-test-conventions).
vitest-tdd-workflow
ACTIVATE when building new features, endpoints, or user stories using TDD with Vitest in a TypeScript/NestJS context. ACTIVATE for '/feature-tdd-dev', 'TDD', 'red-green-refactor' in TS context. Provides Vitest/NestJS-specific TDD examples and commands; cross-language TDD workflow (cross-layer iterations, RED-GREEN-REFACTOR, working app, bug-fix-first-test, mocks-hiding-bugs) lives in craft:tdd-workflow-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), test writing conventions (see vitest:vitest-test-conventions), PHP TDD (see phpunit:php-tdd-workflow).
ts-refactoring
ACTIVATE when refactoring TypeScript code. ACTIVATE for 'refactor', 'extract', 'redesign', 'simplify', or 'clean up' in a TypeScript / Node / NestJS context. This skill provides TS-specific examples for the cross-language refactoring rules defined in craft:refactoring-principles. DO NOT use for: writing new features from scratch, general OOP patterns (see ts-oop).
ts-ports-adapters
ACTIVATE when a TypeScript codebase with no dependency-injection container has to declare a port and wire its adapter — a repository, a clock, an id generator, an event dispatcher the domain depends on. ACTIVATE for 'port', 'adapter', 'SPI', 'dependency inversion' or 'composition root' in a codebase that wires its dependencies by hand. Covers: the port as a type of functions in the domain layer, the adapter as an object literal annotated with it, the handler that takes its dependencies first and its data second, the composition root in the infrastructure layer, and the in-memory stub that substitutes for the adapter in a unit test. DO NOT use for: NestJS, or any container-based DI with decorators and tokens (see nest-ddd-conventions), aggregate operations and smart constructors (see ddd-ts-fp), the Result type itself (see ts-functional).
ts-oop
ACTIVATE when designing TypeScript classes, and the value objects or collections modelled as classes, or when the user asks about object design, encapsulation, Tell Don't Ask, or Symbol.iterator. Provides TS-specific examples for the cross-language OOP rules defined in craft:oop-principles, plus TS-specific patterns (Symbol.iterator, branded types for primitive identifiers). DO NOT use for: a value object or an aggregate modelled as an immutable record rather than a class (see ddd-ts-fp), refactoring methodology (see ts-refactoring).
ts-layer-boundaries
ACTIVATE when wiring a Worker entry point, a Router, a controller, or a domain event consumer in a TypeScript CQRS codebase, or when deciding where a port belongs. ACTIVATE for 'composition root', 'layer boundary', 'ESLint zones', 'domain must not import infrastructure'. Covers: the *Worker.ts composition root, the curried consumer, Router wiring of command endpoints, the five-gesture controller, the domain-to-infrastructure import boundary enforced by ESLint, infrastructure-only ports, in-memory doubles for every port, the read-can-reach-write asymmetry, and read endpoints going through a domain handler. DO NOT use for: the port's own shape and adapter binding (see ts-ports-adapters), the Result type (see ts-functional), domain event structure (see ts-ddd-events).