Skip to content

Commit ce69d14

Browse files
f-lab-pizclaude
andcommitted
feat: Alembic 초기 마이그레이션 설정
- Dockerfile에 alembic.ini 및 alembic 디렉토리 복사 추가 - 초기 마이그레이션 생성 (items 테이블) - plan.md에 Alembic 기본 개념 및 사용법 문서화 - 핵심 개념: Migration, Revision, upgrade/downgrade - 주요 명령어 정리 - 마이그레이션 파일 구조 설명 - 환경 설정 방법 학습 내용: - Alembic은 SQLAlchemy 기반 DB 마이그레이션 도구 - revision --autogenerate로 모델 변경 자동 감지 - upgrade/downgrade로 스키마 버전 관리 - 각 마이그레이션은 고유 revision ID로 추적 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent c45dcd2 commit ce69d14

File tree

3 files changed

+106
-3
lines changed

3 files changed

+106
-3
lines changed

Dockerfile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@ RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
1111
COPY requirements.txt .
1212
RUN pip install --no-cache-dir -r requirements.txt
1313

14-
# 애플리케이션 코드 복사 (app 디렉토리만)
14+
# 애플리케이션 코드 복사
1515
COPY app ./app
16+
COPY alembic.ini .
17+
COPY alembic ./alembic
1618

1719
# 포트 8000 노출
1820
EXPOSE 8000
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""Initial migration: create items table
2+
3+
Revision ID: 0fee3ec0c79f
4+
Revises:
5+
Create Date: 2025-10-10 02:45:22.418966
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '0fee3ec0c79f'
14+
down_revision = None
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade() -> None:
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('items',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('name', sa.String(), nullable=True),
24+
sa.Column('description', sa.String(), nullable=True),
25+
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
26+
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
27+
sa.PrimaryKeyConstraint('id')
28+
)
29+
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
30+
op.create_index(op.f('ix_items_name'), 'items', ['name'], unique=False)
31+
# ### end Alembic commands ###
32+
33+
34+
def downgrade() -> None:
35+
# ### commands auto generated by Alembic - please adjust! ###
36+
op.drop_index(op.f('ix_items_name'), table_name='items')
37+
op.drop_index(op.f('ix_items_id'), table_name='items')
38+
op.drop_table('items')
39+
# ### end Alembic commands ###

plan.md

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,70 @@ locust
5151
- DeploymentTestUser: 무중단 배포 검증
5252
- StressTestUser: 스트레스 테스트
5353

54+
### 6단계: Alembic 데이터베이스 마이그레이션 ⏳
55+
#### 6-1. Alembic 기본 개념 ✅
56+
Alembic은 SQLAlchemy를 위한 데이터베이스 마이그레이션 도구입니다.
57+
58+
**핵심 개념:**
59+
- **마이그레이션 (Migration)**: 데이터베이스 스키마 변경을 추적하는 버전 관리 시스템
60+
- **Revision**: 각 마이그레이션의 고유 ID (예: 0fee3ec0c79f)
61+
- **upgrade()**: 스키마를 최신 버전으로 업데이트하는 함수
62+
- **downgrade()**: 이전 버전으로 롤백하는 함수
63+
64+
**주요 명령어:**
65+
```bash
66+
# 마이그레이션 파일 자동 생성 (모델 변경 감지)
67+
alembic revision --autogenerate -m "설명"
68+
69+
# 데이터베이스에 마이그레이션 적용
70+
alembic upgrade head
71+
72+
# 한 단계 롤백
73+
alembic downgrade -1
74+
75+
# 현재 마이그레이션 상태 확인
76+
alembic current
77+
78+
# 마이그레이션 히스토리 확인
79+
alembic history
80+
```
81+
82+
**마이그레이션 파일 구조:**
83+
- `alembic/versions/` 디렉토리에 생성됨
84+
- 파일명: `{revision_id}_{message}.py`
85+
- upgrade() 함수: 스키마 변경 적용
86+
- downgrade() 함수: 변경 사항 되돌리기
87+
88+
**환경 설정:**
89+
- `alembic/env.py`: Alembic 환경 설정 (DB 연결 등)
90+
- `alembic.ini`: Alembic 설정 파일
91+
- DATABASE_URL 환경변수로 DB 연결 정보 제공
92+
93+
**초기 마이그레이션 생성:**
94+
1. Dockerfile에 alembic 파일 복사 추가
95+
2. 로컬에서 마이그레이션 생성: `python3 -m alembic revision --autogenerate -m "Initial migration"`
96+
3. 생성된 파일 확인: `alembic/versions/0fee3ec0c79f_initial_migration_create_items_table.py`
97+
98+
**생성된 마이그레이션 내용:**
99+
- items 테이블 생성
100+
- id (PK), name, description 컬럼
101+
- created_at, updated_at 타임스탬프
102+
- name, id에 인덱스 생성
103+
104+
#### 6-2. 스키마 변경 실습
105+
- [ ] Item 모델에 컬럼 추가 (price, stock)
106+
- [ ] 마이그레이션 생성 및 적용
107+
- [ ] upgrade/downgrade 테스트
108+
109+
#### 6-3. 무중단 배포 통합
110+
- [ ] deploy.sh에 마이그레이션 자동화
111+
- [ ] 배포 전 마이그레이션 실행
112+
- [ ] 실패 시 롤백 로직
113+
114+
#### 6-4. 데이터 마이그레이션
115+
- [ ] 데이터 변환 마이그레이션 작성
116+
- [ ] op.execute() 사용법
117+
54118
### 다음 단계 계획
55-
- [ ] 데이터베이스 마이그레이션 자동화
56-
- [ ] 배포 스크립트 개선 (롤백 기능)
57119
- [ ] 모니터링 및 로깅 추가
58120
- [ ] 실제 배포 테스트 및 문서화

0 commit comments

Comments
 (0)