Files
lobehub/.cursor/rules/db-migrations.mdc
2026-01-13 22:10:48 +08:00

47 lines
1.5 KiB
Plaintext

---
globs: packages/database/migrations/**/*
alwaysApply: false
---
# Database Migrations Guide
## Step1: Generate migrations
```bash
bun run db:generate
```
this step will generate following files:
- packages/database/migrations/0046_meaningless_file_name.sql
- packages/database/migrations/0046_meaningless_file_name.sql
and update the following files:
- packages/database/migrations/meta/\_journal.json
- packages/database/src/core/migrations.json
- docs/development/database-schema.dbml
## Step2: optimize the migration sql fileName
the migration sql file name is randomly generated, we need to optimize the file name to make it more readable and meaningful. For example, `0046_meaningless_file_name.sql` -> `0046_user_add_avatar_column.sql`
## Step3: Defensive Programming - Use Idempotent Clauses
Always use defensive clauses to make migrations idempotent:
```sql
-- ✅ Good: Idempotent operations
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" text;
DROP TABLE IF EXISTS "old_table";
CREATE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email");
ALTER TABLE "posts" DROP COLUMN IF EXISTS "deprecated_field";
-- ❌ Bad: Non-idempotent operations
ALTER TABLE "users" ADD COLUMN "avatar" text;
DROP TABLE "old_table";
CREATE INDEX "users_email_idx" ON "users" ("email");
```
**Important**: After modifying migration SQL (e.g., adding `IF NOT EXISTS` clauses), run `bun run db:generate:client` to update the hash in `packages/database/src/core/migrations.json`.