← 返回列表
全部 Skill›数据与AI Data & AI›db-migrations

db-migrations

作者 @lobehub · 语言 en
Use for Drizzle migration rollout, online indexes, backfills, idempotent SQL and migration regeneration or rebase conflicts.
数据与AI Data & AI数据工程通用执行命令敏感路径待翻译
最近源活动
—
检测 SKILL.md 语言
en
星标 ★
85,861
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

Database Migrations Guide

Schema conventions

Apply these before generating any migration — they change what the schema file looks like, not just the SQL.

  • No pg enums (and no fixed value sets) for growing domains. For columns whose value set will keep expanding (resource types, statuses, providers, …), use a plain text column typed via .$type<UnionType>(). pgEnum requires an ALTER TYPE ... ADD VALUE migration for every new literal, and even the Drizzle text('col', { enum: [...] }) option hardwires the value list into the schema file. With .$type<>(), onboarding a new value is a type-only change — no migration at all.

```ts

// ✅ Good — type lives in @lobechat/types, column stays plain text

resourceType: text('resource_type').$type<TransferResourceType>().notNull(),

// ❌ Bad — pg enum, needs ALTER TYPE per new value

resourceType: resourceTypeEnum('resource_type').notNull(),

// ❌ Avoid — value list hardwired into the schema file

resourceType: text('resource_type', { enum: TRANSFER_RESOURCE_TYPES }).notNull(),

```

  • Keep domain constants out of schema files. In new or modified schema files under packages/database/src/schemas/, shared domain literal arrays, union types, and option interfaces belong in @lobechat/types (one module per domain, re-exported from its index.ts); both the schema (.$type<>()) and consumers (routers via z.enum(...), services, UI) import from there. This rule targets domain constants only — table objects, inferred row types, Drizzle relation objects, and zod insert/select schemas (insertAgentSchema, …) are the schema file's job and stay put. Existing schema files that already export such constants (e.g. resourcePermission.ts) are grandfathered; migrate them opportunistically when the file is next touched, not in bulk.
  • Prefixed ids only for rows that are addressed one at a time. An idGenerator prefix (task_, cmt_, brf_) earns its keep when the id turns up somewhere a person reads it — a URL segment, an API argument, a tool-call payload, a support ticket. A child table whose rows are only ever fetched in bulk for their parent takes a plain uuid instead, like task_dependencies / task_documents / task_topics; there the prefix costs a registry entry in idGenerator.ts and buys nothing back.

```ts

// ✅ Addressed individually — deleteComment(commentId), /task/:id

id: text('id')

.primaryKey()

.$defaultFn(() => idGenerator('taskComments'))

.notNull(),

// ✅ Only ever read in bulk for one parent

id: uuid('id').defaultRandom().primaryKey().notNull(),

```

  • Column order: identity → scope → the table's own columns → visibility → timestamps. Put id and the parent FK first, then the ownership columns (user_id, workspace_id), then whatever this table is actually for, then visibility, then the ...timestamps / createdAt() spread. A reader scanning an unfamiliar table then finds the same field in the same place. visibility sitting at the end is the deliberate slot, not an accident of history: of the 22 tables that carry the column today, 17 place it in the last three columns and none place it directly after id. A new table that hoists it to the front becomes the one outlier — if the placement is ever worth changing, change it repo-wide and update this rule, not one table at a time.

Choose the rollout strategy

Classify every database change into one of these three rollout paths before generating or editing a migration.

Validate rollout assumptions on the actual Dev database

Do not choose a rollout path from hypothetical claims such as “this migration might be slow” or “installing these triggers could block deployment.” Before deciding that a schema change needs a manual production step, deferred installation, or a dedicated backfill, test the relevant operation against the project's actual Dev database.

  • Classify the database target first using the project's approved database-access tooling; never read secret-bearing .env files directly.
  • Measure the real operation or the closest safe equivalent, such as creating an identically defined probe index under a temporary name or installing temporary triggers inside a transaction that is rolled back.
  • Record the tested SQL or operation, representative row count and table size, elapsed time, and cleanup verification.
  • Keep probes reversible and remove every temporary database object after the measurement.
  • Treat a single Dev result as evidence about the observed Dev scale, not proof of production behavior. State material differences in production scale, load, cache state, and lock contention explicitly, and label any resulting production claim as an inference.

Rollout decisions must combine repository deployment facts with these measurements. Do not add operational tables, delayed activation paths, or manual release steps solely to guard against unmeasured performance concerns.

1. Regular Drizzle migration

Use the normal Drizzle workflow for schema changes that are safe to execute during deployment, such as creating a small table or adding a nullable column:

  1. Update the Drizzle schema.
  2. Run bun run db:generate.
  3. Review and harden the generated artifacts using the steps below.

Before listing a manual migration command as a release step, inspect the target repository's build and deployment scripts. If its deployment pipeline already applies migrations automatically, do not require a redundant manual run.

2. Online index creation

Creating an index normally can block writes and queries on a large or frequently accessed table, and a long-running statement can also stall the deployment. In that case:

  1. Before deploying the application, execute the index creation manually in the target dat
评论
Llobehub
lobehub
lobehub/lobehub
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@lobehub
所属大类数据与AI Data & AI / 数据工程
国内可用性通用
最近源活动—
风险提示执行命令、敏感路径
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。