Database Migrations
Approach
Section titled “Approach”D1 migrations are managed as numbered SQL files in db/migrations/. The canonical schema is maintained in db/schema.sql.
Creating a Migration
Section titled “Creating a Migration”Use the /db-migrate Claude Code command:
/db-migrateOr manually:
- Create
db/migrations/NNNN_description.sqlwith the SQL changes - Apply locally:
wrangler d1 execute dotcollective-tools-db --local --file=db/migrations/NNNN_description.sql - Update
db/schema.sqlto reflect the current state - Test locally
- Apply to production before deploy:
wrangler d1 execute dotcollective-tools-db --remote --file=db/migrations/NNNN_description.sql
Best Practices
Section titled “Best Practices”- Use
CREATE TABLE IF NOT EXISTSandCREATE INDEX IF NOT EXISTSfor idempotent schema - Use
INSERT OR REPLACEfor seed data that may already exist - Always update
db/schema.sqlto match the current state after migrations - Test migrations locally before applying to production
- Back up production data before destructive migrations (D1 supports point-in-time recovery)