db-migrations
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
textcolumn typed via.$type<UnionType>().pgEnumrequires anALTER TYPE ... ADD VALUEmigration for every new literal, and even the Drizzletext('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 itsindex.ts); both the schema (.$type<>()) and consumers (routers viaz.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
idGeneratorprefix (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, liketask_dependencies/task_documents/task_topics; there the prefix costs a registry entry inidGenerator.tsand 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. Putidand the parent FK first, then the ownership columns (user_id,workspace_id), then whatever this table is actually for, thenvisibility, then the...timestamps/createdAt()spread. A reader scanning an unfamiliar table then finds the same field in the same place.visibilitysitting 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 afterid. 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
.envfiles 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:
- Update the Drizzle schema.
- Run
bun run db:generate. - 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:
- Before deploying the application, execute the index creation manually in the target dat
