主题
集成 Drizzle
以 VfanHub 的 PostgreSQL 接入为例,使用
@nestjs/drizzle、drizzle-orm和pg
安装依赖
bash
pnpm add @nestjs/drizzle @nestjs/config drizzle-orm pg
pnpm add -D drizzle-kit @types/pg详细说明
@nestjs/drizzle:Nest 官方 Drizzle 集成,提供DrizzleModule与@InjectDrizzle()。drizzle-orm:Drizzle ORM。drizzle-kit:生成与执行迁移。pg/@types/pg:node-postgres 驱动及其类型。@nestjs/config:通过ConfigService读取DATABASE_URL。
环境变量
md
DATABASE_URL=postgres://app_user:app_password@localhost:5432/app_dbAPI、Drizzle Kit 和 seed 共用 DATABASE_URL。VfanHub 通过 loadEnv() 定位并加载 apps/api/.env,同名进程变量优先。API 再通过全局 ConfigService 读取配置,连接选项由数据库模块集中校验。
推荐目录
bash
project/
├── src/
│ ├── app.module.ts
│ ├── infrastructure/
│ │ └── database/
│ │ ├── database.module.ts # 注册连接与启动检查
│ │ ├── database-config.service.ts
│ │ ├── database.types.ts
│ │ └── schema.ts # Nest 与 Drizzle Kit 共用的表定义
│ └── modules/
│ └── notes/
│ ├── notes.module.ts
│ └── notes.service.ts
├── db/ # seed、连通性检查、可选业务 SQL
├── drizzle/ # 生成的迁移文件与元数据
└── drizzle.config.ts定义 Schema
ts
import { pgTable, text, uuid } from 'drizzle-orm/pg-core'
export const notes = pgTable('notes', {
id: uuid('id').defaultRandom().primaryKey(),
title: text('title').notNull(),
content: text('content').notNull(),
})
export type Note = typeof notes.$inferSelect
export type NewNote = typeof notes.$inferInsert$inferSelect / $inferInsert 从列定义推导行类型,无需再维护独立模型类。
常见字段习惯:
- 主键优先使用
uuid或 PostgreSQL identity。 - 时间点优先使用
timestamp(..., { withTimezone: true })。 - 金额使用
numeric,不要使用浮点数。 - 需要 JSON 查询和索引时使用
jsonb。
配置 Drizzle Kit
ts
import { defineConfig } from 'drizzle-kit'
import { relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { loadEnv } from './src/config/env.js'
loadEnv()
const databaseUrl = process.env.DATABASE_URL
export default defineConfig({
dialect: 'postgresql',
schema: fileURLToPath(new URL('./src/infrastructure/database/schema.ts', import.meta.url)),
// Drizzle Kit 0.31 读取已有快照时要求输出目录为相对路径
out: relative(process.cwd(), fileURLToPath(new URL('./drizzle/', import.meta.url))),
dbCredentials: databaseUrl?.trim() ? { url: databaseUrl } : undefined,
strict: true,
})generate 根据 Schema 和已有快照生成迁移,可以离线执行。migrate 和 Studio 需要目标数据库连接。
生成和执行迁移
json
{
"scripts": {
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:seed": "tsx db/seed/index.ts",
"db:smoke": "tsx db/smoke/index.ts",
"db:studio": "drizzle-kit studio --host=127.0.0.1"
}
}pnpm db:generate后审查 SQL,将迁移及其元数据一起提交pnpm db:migrate独立于 API 启动运行,只应用尚未执行的迁移pnpm db:seed显式初始化基础数据。VfanHub 用它初始化权限、菜单、超管角色和账号。可选业务 SQL 由维护者按需导入
注册数据库模块
根模块导入 DatabaseModule。VfanHub 用 forRootAsync({ useClass: DatabaseConfigService }) 注册单个全局实例,并在模块初始化时执行 SELECT 1 检查连接。
ts
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import type { DrizzleModuleFactoryOptions, DrizzleOptionsFactory } from '@nestjs/drizzle'
import { drizzle } from 'drizzle-orm/node-postgres'
import { validateDatabaseUrl } from '../../config/validation.js'
import * as schema from './schema.js'
@Injectable()
export class DatabaseConfigService implements DrizzleOptionsFactory {
/** 注入 API 配置 */
constructor(private readonly config: ConfigService) {}
/** 返回连接池与 Schema 配置 */
createDrizzleOptions(): DrizzleModuleFactoryOptions {
return {
drizzle,
schema,
connection: {
connectionString: validateDatabaseUrl(this.config.getOrThrow<string>('DATABASE_URL')),
max: 10,
connectionTimeoutMillis: 5000,
statement_timeout: 10000,
},
}
}
}ts
import { Module, type OnModuleInit } from '@nestjs/common'
import { DrizzleModule, InjectDrizzle } from '@nestjs/drizzle'
import { sql } from 'drizzle-orm'
import { DatabaseConfigService } from './database-config.service.js'
import type { Database } from './database.types.js'
@Module({
imports: [DrizzleModule.forRootAsync({ useClass: DatabaseConfigService })],
})
export class DatabaseModule implements OnModuleInit {
/** 注入全局数据库实例 */
constructor(@InjectDrizzle() private readonly db: Database) {}
/** 检查数据库连接 */
async onModuleInit() {
await this.db.execute(sql`SELECT 1`)
}
}要点:
drizzle传入对应驱动的drizzle()函数;connection可为连接串,或pg连接池配置对象。- 传入
schema后可使用db.query关系查询(Drizzle v0.x)。 - 默认
autoCloseConnection: true,应用关闭时会结束底层连接池,无需手写关池逻辑。 - 注册后数据库在应用内全局可用,业务模块通过
@InjectDrizzle()注入即可。
通过 NodePgDatabase<typeof schema> 保留关系查询的类型。可从数据库实例推导事务类型,让复用查询接受数据库或调用方传入的事务:
ts
import type { NodePgDatabase } from 'drizzle-orm/node-postgres'
import type * as schema from './schema.js'
export type Database = NodePgDatabase<typeof schema>
export type Transaction = Parameters<Parameters<Database['transaction']>[0]>[0]
export type QueryDb = Database | Transaction在业务服务中使用
ts
import { Injectable, NotFoundException } from '@nestjs/common'
import { InjectDrizzle } from '@nestjs/drizzle'
import { eq, ilike } from 'drizzle-orm'
import { notes } from '../../infrastructure/database/schema.js'
import type { Database } from '../../infrastructure/database/database.types.js'
import type { CreateNoteDto } from './dto/create-note.dto.js'
import type { UpdateNoteDto } from './dto/update-note.dto.js'
@Injectable()
export class NotesService {
/** 注入数据库实例 */
constructor(@InjectDrizzle() private readonly db: Database) {}
/** 创建笔记 */
async create(dto: CreateNoteDto) {
const [row] = await this.db.insert(notes).values(dto).returning()
return row
}
/** 按标题筛选笔记 */
async getAll(title?: string) {
const query = this.db.select().from(notes)
if (title) {
return await query.where(ilike(notes.title, `%${title}%`))
}
return await query
}
/** 查询指定笔记 */
async getOne(id: string) {
const [row] = await this.db.select().from(notes).where(eq(notes.id, id))
if (!row) throw new NotFoundException('Note not found')
return row
}
/** 更新指定笔记 */
async update(id: string, dto: UpdateNoteDto) {
await this.getOne(id)
const [row] = await this.db.update(notes).set(dto).where(eq(notes.id, id)).returning()
return row
}
/** 删除指定笔记 */
async delete(id: string) {
await this.getOne(id)
const [row] = await this.db.delete(notes).where(eq(notes.id, id)).returning()
return row
}
}表定义是普通对象,直接 import,不需要 forFeature()。返回值由 Drizzle 根据 schema 推导;请求输入仍用 Nest 的 class-validator、zod 等方案校验。
事务
ts
await this.db.transaction(async (tx) => {
const [note] = await tx.insert(notes).values({ title: 't', content: 'c' }).returning()
return note
})事务内部统一使用 tx。以邮箱验证码为例,VfanHub 通过行锁避免同一个验证码被并发消费,校验成功时在同一事务更新账号并删除验证码。校验失败时先提交错误次数,再在事务外返回错误,避免抛异常回滚计数。
Nest 外脚本(可选)
种子、冒烟检测等脚本不走 Nest DI 时,可单独创建 Drizzle 实例:
ts
import { drizzle } from 'drizzle-orm/node-postgres'
import { sql } from 'drizzle-orm'
import { Pool } from 'pg'
import { loadEnv } from '../../src/config/env.js'
import { validateDatabaseUrl } from '../../src/config/validation.js'
import * as schema from '../../src/infrastructure/database/schema.js'
loadEnv()
const pool = new Pool({
connectionString: validateDatabaseUrl(process.env.DATABASE_URL ?? ''),
})
try {
const db = drizzle(pool, { schema })
await db.execute(sql`SELECT 1`)
} finally {
await pool.end()
}独立脚本负责关闭自己的连接。多个 Nest 应用实例确需共享一个外部创建的 db 时,由创建方统一管理连接生命周期,并为各实例关闭 autoCloseConnection。
