skills/doyajin174/database-migration/SKILL.md
Manage database schema changes with version control. Use when modifying DB schema, adding tables/columns, or setting up new projects. Covers Prisma, Drizzle, and migration best practices.
npx skillsauth add aiskillstore/marketplace database-migrationInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
데이터베이스 스키마 변경을 버전 관리하는 스킬입니다.
"DB 스키마도 코드처럼 버전 관리한다." "수동으로 ALTER TABLE 치는 순간, 협업이 망가진다."
| 규칙 | 상태 | 설명 | |------|------|------| | 마이그레이션 파일 생성 | 🔴 필수 | 수동 SQL 실행 금지 | | 롤백 가능 | 🔴 필수 | down migration 필수 | | 순차 실행 | 🔴 필수 | 마이그레이션 순서 보장 | | 프로덕션 백업 | 🔴 필수 | 마이그레이션 전 백업 |
# Prisma 설치
npm install prisma @prisma/client
# 초기화
npx prisma init
# .env에 DATABASE_URL 설정
# DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
# 1. 스키마 변경 후 마이그레이션 생성
npx prisma migrate dev --name add_user_table
# 2. 마이그레이션 파일 확인
ls prisma/migrations/
# 3. 프로덕션 배포
npx prisma migrate deploy
# 4. 클라이언트 재생성
npx prisma generate
prisma/
├── schema.prisma
└── migrations/
├── 20240101000000_init/
│ └── migration.sql
├── 20240102000000_add_user_table/
│ └── migration.sql
└── migration_lock.toml
# 개발: 마이그레이션 생성 + 적용
npx prisma migrate dev --name <migration_name>
# 프로덕션: 마이그레이션만 적용
npx prisma migrate deploy
# 상태 확인
npx prisma migrate status
# 리셋 (⚠️ 개발용만)
npx prisma migrate reset
# Drizzle 설치
npm install drizzle-orm postgres
npm install -D drizzle-kit
// src/db/schema.ts
import { pgTable, serial, text, timestamp, boolean, integer } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: text('email').notNull().unique(),
name: text('name'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content'),
published: boolean('published').default(false),
authorId: integer('author_id').references(() => users.id),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
import type { Config } from 'drizzle-kit';
export default {
schema: './src/db/schema.ts',
out: './drizzle',
driver: 'pg',
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
} satisfies Config;
# 마이그레이션 생성
npx drizzle-kit generate:pg
# 마이그레이션 적용
npx drizzle-kit push:pg
# 스키마 시각화
npx drizzle-kit studio
-- ❌ BAD: 한 번에 많은 변경
-- migration: big_refactor
ALTER TABLE users ADD COLUMN age INT;
ALTER TABLE users ADD COLUMN address TEXT;
ALTER TABLE users DROP COLUMN old_field;
CREATE TABLE new_table (...);
DROP TABLE old_table;
-- ✅ GOOD: 작은 단위로 분리
-- migration: add_user_age
ALTER TABLE users ADD COLUMN age INT;
-- migration: add_user_address
ALTER TABLE users ADD COLUMN address TEXT;
-- ❌ BAD: NOT NULL without default (기존 데이터 문제)
ALTER TABLE users ADD COLUMN status TEXT NOT NULL;
-- ✅ GOOD: default 값 포함
ALTER TABLE users ADD COLUMN status TEXT NOT NULL DEFAULT 'active';
-- 또는 nullable로 추가 후 나중에 마이그레이션
ALTER TABLE users ADD COLUMN status TEXT;
UPDATE users SET status = 'active' WHERE status IS NULL;
ALTER TABLE users ALTER COLUMN status SET NOT NULL;
-- ❌ BAD: 바로 삭제
ALTER TABLE users DROP COLUMN old_field;
-- ✅ GOOD: 단계적 삭제
-- Step 1: 코드에서 컬럼 사용 제거
-- Step 2: 배포 후 안정화 확인
-- Step 3: 마이그레이션으로 컬럼 삭제
-- ❌ BAD: 큰 테이블에 동기 인덱스 생성 (락 발생)
CREATE INDEX idx_users_email ON users(email);
-- ✅ GOOD: CONCURRENTLY 사용 (PostgreSQL)
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
# 마지막 마이그레이션 롤백
npx prisma migrate resolve --rolled-back <migration_name>
# 또는 특정 시점으로 복구
npx prisma migrate reset # ⚠️ 개발용만!
-- migrations/20240102_add_status/down.sql
ALTER TABLE users DROP COLUMN status;
# .github/workflows/migrate.yml
name: Database Migration
on:
push:
branches: [main]
paths:
- 'prisma/**'
jobs:
migrate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Run migrations
run: npx prisma migrate deploy
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
# PR에서 마이그레이션 유효성 검사
jobs:
validate-migration:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- name: Run migrations on test DB
run: npx prisma migrate deploy
env:
DATABASE_URL: postgresql://postgres:test@localhost:5432/test
1. 스키마 파일 수정 (schema.prisma)
2. npx prisma migrate dev --name <description>
3. 생성된 SQL 확인
4. Git 커밋 (스키마 + 마이그레이션 파일)
1. PR 머지
2. CI에서 npx prisma migrate deploy 실행
3. 프로덕션 확인
4. (문제 시) 롤백 실행
development
Apple Human Interface Guidelines for content display components. Use this skill when the user asks about charts component, collection view, image view, web view, color well, image well, activity view, lockup, data visualization, content display, displaying images, rendering web content, color pickers, or presenting collections of items in Apple apps. Also use when the user says how should I display charts, what's the best way to show images, should I use a web view, how do I build a grid of items, what component shows media, or how do I present a share sheet. Cross-references: hig-foundations for color/typography/accessibility, hig-patterns for data visualization patterns, hig-components-layout for structural containers, hig-platforms for platform-specific component behavior.
tools
Automate HelpDesk tasks via Rube MCP (Composio): list tickets, manage views, use canned responses, and configure custom fields. Always search tools first for current schemas.
testing
Expert Haskell engineer specializing in advanced type systems, pure functional design, and high-reliability software. Use PROACTIVELY for type-level programming, concurrency, and architecture guidance.
tools
GraphQL gives clients exactly the data they need - no more, no less. One endpoint, typed schema, introspection. But the flexibility that makes it powerful also makes it dangerous. Without proper controls, clients can craft queries that bring down your server. This skill covers schema design, resolvers, DataLoader for N+1 prevention, federation for microservices, and client integration with Apollo/urql. Key insight: GraphQL is a contract. The schema is the API documentation. Design it carefully.