728x90

alembic이란?

SQLAlchemy의 확장으로, 데이터베이스 스키마의 버전관리를 위한 도구

데이터베이스 마이그레이션, 스키마 버전관리, 백업 등의 기능을 제공

alembic의 주요 특징

  • 마이그레이션 지원 : 데이터베이스 스키마를 업데이트하거나 변경할 때 사용되는 마이그레이션 스크립트를 생성하고 관리
  • 버전관리 지원 : 각 마이그레이션은 버전으로 관리되며, 데이터베이스 스키마의 특정 버전으로 이동 가능
  • 다양한 데이터베이스 지원 : SQLAlchemy를 기반으로 하기 때문에 다양한 데이터베이스 엔진 지원
  • 명령행 도구 지원 : 명령행도구를 제공하여 터미널에서 간편하게 마이그레이션 수행 가능

alembic 설치

pip install alembic

alembic 기초 사용법

1. 초기 세팅

alembic init alembic

 

생성된 alembic.ini 파일을 열어 데이터베이스 연결 정보를 설정

# alembic.ini 예시
[alembic]
script_location = alembic 
sqlalchemy.url = driver://user:password@dbhost:dbport/dbname

# script_location : 마이그레이션 스크립트 위치
# model_location : models.py 위치, 설정된 디렉토리 내에 있는 모든 Python 파일을 모델로 인식

 

2. SQLAlchemy 모델 정의 (이미 정의된 모델이 있다면 pass)

# models.py 예시
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)

 

3. 마이그레이션 스크립트 생성

변경된 모델을 기반으로 마이그레이션 스크립트 자동으로 생성됨

alembic revision --autogenerate -m "message"

 

생성된 스크립트를 열어보면 Alembic이 모델의 변경사항을 감지하고 스키마를 업데이트하기 위한 SQL 명령어를 생성한 것을 확인할 수 있음

# 생성된 스크립트 예시 my_migration/versions/<timestamp>_message.py
from alembic import op
import sqlalchemy as sa

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

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

 

4. 마이그레이션 적용

# 최신버전으로 업그레이드
alembic upgrade head

# 특정 버전으로 업그레이드
alembic upgrade {revision_number}

# 최초 버전으로 다운그레이드
alembic downgrade base

# 특정버전으로 다운그레이드
alembic downgrade {revision_number}

참고

alembic 공식문서 튜토리얼

728x90

+ Recent posts