본문으로 건너뛰기
cccskills
무료GitHub에 공개

drizzle-migrations

Manage database schema with Drizzle ORM and SQLite migrations. Use when adding tables, modifying columns, creating indexes, or running migrations. Activates for database schema changes, migration generation, and Drizzle query patterns.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

연동 도구SupabasePostgreSQL
설치 방법 보기

포함된 파일(1)

  • SKILL.md7.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Drizzle ORM Migrations

Manage database schema changes using Drizzle ORM with SQLite through decision-driven migration strategies.

DECISION POINTS

Schema Change Strategy Decision Tree

Is this a production database?
├─ YES → Always use generate + migrate workflow
│  ├─ Breaking change (column removal, type change)?
│  │  ├─ YES → Multi-step migration with data preservation
│  │  └─ NO → Standard migration generation
│  └─ Performance impact (large table, complex index)?
│     ├─ YES → Plan maintenance window, test on replica
│     └─ NO → Standard migration during low traffic
└─ NO (development) → Can use push for speed
   ├─ Breaking existing local data?
   │  ├─ YES → Backup first, consider fresh DB
   │  └─ NO → Safe to push directly
   └─ Collaborating with team?
      ├─ YES → Use migrations for consistency
      └─ NO → Push is acceptable

Column Type Selection Matrix

Data TypeUseDrizzle TypeIndex Recommended
User IDPrimary/Foreign keystext('id').primaryKey()Auto on PK/FK
EmailUnique identifierstext('email').unique()YES
TimestampsCreated/updated timestext('created_at').default(sql\CURRENT_TIMESTAMP`)`If filtered
JSON DataFlexible schemastext('data', { mode: 'json' })NO (use computed)
BooleansStatus flagsinteger('active', { mode: 'boolean' })If filtered
CountersStats, quantitiesinteger('count').default(0)If aggregated

Migration Conflict Resolution

Migration fails to apply?
├─ Schema conflict detected
│  ├─ Column exists → Check if type matches expected
│  ├─ Table exists → Verify schema matches or rename
│  └─ Index exists → Check if definition identical
├─ Foreign key violation
│  ├─ Referenced table missing → Create dependency first
│  ├─ Referenced column missing → Fix reference or add column
│  └─ Circular reference → Break into separate migrations
└─ Data type mismatch
   ├─ Incompatible conversion → Create transformation migration
   ├─ NULL constraint violation → Add default or migrate data
   └─ Unique constraint violation → Clean duplicate data first

FAILURE MODES

1. "Push to Production" Anti-Pattern

Symptoms: Using npm run db:push on production database Detection: If environment is production AND using push command Fix:

  • Stop immediately
  • Generate proper migration: npm run db:generate
  • Review SQL in /drizzle folder
  • Test on staging first
  • Apply via migration runner

2. "Missing Index Cascade" Anti-Pattern

Symptoms: Query performance degrades after adding foreign keys Detection: Foreign key columns without corresponding indexes Fix:

// Add index for FK columns
export const checkIns = sqliteTable('check_ins', {
  userId: text('user_id').notNull().references(() => users.id),
}, (table) => ({
  userIdIdx: index('idx_checkins_user_id').on(table.userId), // Add this
}));

3. "Destructive Migration Drift" Anti-Pattern

Symptoms: Data loss during column rename or type changes Detection: Migration contains DROP COLUMN or incompatible type changes Fix:

  • Create multi-step migration
  • Step 1: Add new column
  • Step 2: Migrate data
  • Step 3: Remove old column

4. "Schema Bloat" Anti-Pattern

Symptoms: Tables with 15+ columns, deeply nested JSON in text fields Detection: Single table handling multiple concerns Fix:

  • Break into related tables with proper foreign keys
  • Extract JSON objects into separate tables
  • Use relations to maintain referential integrity

5. "Missing WHERE Clause Disaster" Anti-Pattern

Symptoms: Accidental bulk deletes or updates Detection: DELETE or UPDATE statements without .where() clause Fix:

// WRONG: Deletes all records
await db.delete(users);

// RIGHT: Targeted deletion
await db.delete(users).where(eq(users.id, userId));

WORKED EXAMPLES

Adding a New Table with Relations

Scenario: Add user preferences table to existing user system

Step 1: Analyze Impact

  • New table, no breaking changes
  • Will need FK relationship to users
  • Should include index on user_id for lookups

Step 2: Schema Definition

// src/db/schema.ts
export const userPreferences = sqliteTable('user_preferences', {
  id: text('id').primaryKey(),
  userId: text('user_id').notNull().references(() => users.id, {
    onDelete: 'cascade',  // Delete prefs when user deleted
  }),
  theme: text('theme', { enum: ['light', 'dark', 'auto'] }).default('auto'),
  notifications: integer('notifications', { mode: 'boolean' }).default(true),
  timezone: text('timezone').default('UTC'),
  updatedAt: text('updated_at').notNull().default(sql`CURRENT_TIMESTAMP`),
}, (table) => ({
  userIdIdx: index('idx_user_preferences_user_id').on(table.userId),
}));

export const userPreferencesRelations = relations(userPreferences, ({ one }) => ({
  user: one(users, {
    fields: [userPreferences.userId],
    references: [users.id],
  }),
}));

export const usersRelations = relations(users, ({ one, many }) => ({
  preferences: one(userPreferences),  // Add this line
  checkIns: many(checkIns),
}));

Step 3: Generate and Review

npm run db:generate

Step 4: Verify Generated SQL

-- drizzle/0001_create_user_preferences.sql
CREATE TABLE `user_preferences` (
  `id` text PRIMARY KEY NOT NULL,
  `user_id` text NOT NULL,
  `theme` text DEFAULT 'auto',
  `notifications` integer DEFAULT true,
  `timezone` text DEFAULT 'UTC',
  `updated_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL,
  FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);

CREATE INDEX `idx_user_preferences_user_id` ON `user_preferences` (`user_id`);

What Expert Catches: FK cascade behavior is correct, index is present, defaults are appropriate What Novice Misses: Would forget the index, might not consider cascade behavior

QUALITY GATES

  • Migration generates without errors (npm run db:generate)
  • Generated SQL reviewed for correctness in /drizzle folder
  • Foreign key constraints include proper onDelete behavior
  • Indexes added for all foreign key columns
  • Test database successfully migrates (npm run db:migrate)
  • Sample queries execute without performance issues
  • No data loss verified if modifying existing tables
  • Migration is reversible or rollback plan documented
  • Schema matches TypeScript types (no type/runtime mismatches)
  • Relations properly defined for new tables

NOT-FOR Boundaries

❌ DO NOT use this skill for:

  • PostgreSQL/Supabase projects → Use supabase-admin skill instead
  • Prisma ORM migrations → Different syntax and CLI commands
  • Raw SQL database management → Use database-specific tools
  • Database design theory → Use architecture planning skills
  • Performance tuning → Use database optimization skills
  • Backup/restore operations → Use database administration skills

✅ Instead delegate to:

  • supabase-admin for PostgreSQL schema management
  • database-design for entity relationship modeling
  • sql-optimization for query performance issues

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Expert in 2000s-era music visualization (Milkdrop, AVS, Geiss) and modern WebGL implementations. Specializes in Butterchurn integration, Web Audio API AnalyserNode FFT data, GLSL shaders for audio-reactive visuals, and psychedelic generative art. Activate on "Milkdrop", "music visualization", "WebGL visualizer", "Butterchurn", "audio reactive", "FFT visualization", "spectrum analyzer". NOT for simple bar charts/waveforms (use basic canvas), video editing, or non-audio visuals.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

Expert legal research agent for finding and scraping expungement data state by state. Knows authoritative sources, URL patterns, Firecrawl configuration, and 2026 legal landscape.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

Expert in 3D computer vision labeling tools, workflows, and AI-assisted annotation for LiDAR, point clouds, and sensor fusion. Covers SAM4D/Point-SAM, human-in-the-loop architectures, and vertical-specific training strategies. Activate on '3D labeling', 'point cloud annotation', 'LiDAR labeling', 'SAM 3D', 'SAM4D', 'sensor fusion annotation', '3D bounding box', 'semantic segmentation point cloud'. NOT for 2D image labeling (use clip-aware-embeddings), general ML training (use ml-engineer), video annotation without 3D (use computer-vision-pipeline), or VLM prompt engineering (use prompt-engineer).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

Apply crisis decision-making research to agent routing, uncertainty triage, and coordination failure analysis in time-pressured systems. Use when diagnosing handoff failures, analytical paralysis, or expert judgment under incomplete information. NOT for routine coding, simple CRUD design, or static single-agent tasks with complete information.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

Use for insight, reframing, contradiction, impasse, and anomaly-driven problem solving when execution effort no longer helps. NOT for routine optimization, error correction, or well-specified tasks with known solution paths.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

Apply cognitive task analysis to expert work that depends on perceptual cues, branching judgment, and recurring monitoring loops. Use when decomposing expert capability into agent structure, simulation design, or validation interviews. NOT for ordinary step-by-step SOP capture or simple pipelines with no tacit cue layer.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

curiositech/port-daddy32026년 10월 19일 업데이트

curiositech의 스킬 모두 보기

이 스킬의 문제 신고