Python/fastapi

Alembic 사용법

metamong-data 2025. 1. 8. 19:11
728x90
반응형

개요

Alembic은 SQLAlchemy 기반의 데이터베이스 마이그레이션 도구입니다. 데이터베이스 스키마를 버전 관리하고, 애플리케이션의 변경 사항에 따라 데이터베이스를 업데이트할 수 있습니다.


주요 구성 요소

  1. Environment: Alembic 설정 및 스크립트를 포함하는 디렉터리.

  2. Migration Script: 데이터베이스 스키마 변경 내역이 기록된 Python 스크립트.

  3. Version Table: 현재 데이터베이스 버전을 추적하는 테이블.


기본 사용 흐름

1. 설치

pip install alembic

2. Alembic 초기화

alembic init alembic

이 명령은 alembic 디렉터리를 생성하고 기본 설정 파일(alembic.ini)을 만듭니다.

3. 설정 파일 수정

alembic.ini 파일에서 데이터베이스 URL을 설정합니다.

sqlalchemy.url = sqlite:///example.db

env.py에서 SQLAlchemy Base를 가져오도록 수정합니다.

from my_app.models import Base  # 사용자 정의 Base 경로

target_metadata = Base.metadata

4. 마이그레이션 생성

마이그레이션 스크립트를 생성합니다.

alembic revision --autogenerate -m "create users table"

--autogenerate 옵션은 SQLAlchemy 모델과 데이터베이스 스키마 간의 차이를 자동으로 감지하여 스크립트를 생성합니다.

5. 마이그레이션 적용

alembic upgrade head

이 명령은 데이터베이스를 최신 상태로 업데이트합니다.


예제

1. 초기 모델 생성

from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

2. 테이블 추가 마이그레이션

위 모델을 기반으로 마이그레이션을 생성하고 적용합니다.

alembic revision --autogenerate -m "add users table"
alembic upgrade head

생성된 마이그레이션 스크립트는 다음과 같습니다:

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(), nullable=True),
        sa.Column('age', sa.Integer(), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )

def downgrade():
    op.drop_table('users')

3. 컬럼 추가

새로운 email 컬럼을 추가하는 경우:

alembic revision --autogenerate -m "add email column"

생성된 스크립트:

def upgrade():
    op.add_column('users', sa.Column('email', sa.String(), nullable=True))

def downgrade():
    op.drop_column('users', 'email')

적용 명령:

alembic upgrade head

주요 명령어 요약

  1. 초기화: alembic init alembic

  2. 마이그레이션 생성: alembic revision -m "message"

  3. 자동 생성: alembic revision --autogenerate -m "message"

  4. 업그레이드: alembic upgrade head

  5. 다운그레이드: alembic downgrade -1


참고 자료

  • Alembic 공식 문서

  • SQLAlchemy와 함께 사용하는 Alembic

728x90