drizzle-orm
Drizzle ORM patterns for Neon PostgreSQL. Use when creating tables, schemas, migrations, or database queries.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
Drizzle ORM (Neon PostgreSQL)
Creating a new table
- Create file in
lib/db/schemas/{domain}.ts - Define enum if needed
- Define table with columns and indexes
- Export types
- Re-export from
lib/db/schema.ts
import { pgTable, pgEnum, index, integer, varchar, timestamp } from "drizzle-orm/pg-core"
import type { InferSelectModel, InferInsertModel } from "drizzle-orm"
// 1. Enum (if needed)
export const statusEnum = pgEnum("status", ["active", "inactive"])
// 2. Table with indexes as third argument
export const items = pgTable("items", {
id: integer("id").primaryKey().generatedAlwaysAsIdentity(),
name: varchar("name", { length: 255 }).notNull(),
status: statusEnum("status").notNull(),
created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updated_at: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
}, (table) => [
index("idx_items_name").on(table.name),
])
// 3. Types
export type Item = InferSelectModel<typeof items>
export type InsertItem = InferInsertModel<typeof items>
See examples/schema-pattern.ts for full pattern.
Adding a foreign key
author_id: integer("author_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" })
Always specify onDelete behavior explicitly.
Standard columns
// Primary key
id: integer("id").primaryKey().generatedAlwaysAsIdentity()
// Timestamps (always with timezone)
created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
updated_at: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
Naming conventions
- Index:
idx_{table}_{column}→idx_items_name - One domain per schema file →
songs.ts,dictionary.ts
Avoid
-
serial()→ useinteger().generatedAlwaysAsIdentity() - Timestamps without
{ withTimezone: true } - Foreign keys without explicit
onDelete
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-01-20
- 索引更新时间
- 2026-03-03
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!