SQLAlchemy

[SQLALchemy] Alembic을 이용한 마이그레이션 관리 방법

bluebamus 2025. 1. 31.

1. Alembic 개요

   - Alembic은 SQLAlchemy를 사용하는 Python 애플리케이션에서 데이터베이스 마이그레이션을 관리하는 도구이다.

   - 데이터베이스 스키마를 변경할 때 사용되며, 버전 관리 시스템과 유사하게 데이터베이스 스키마를 체계적으로 관리할 수 있다.

   - 저장소 : https://github.com/bluebamus/sqlalchemy-alembic-study

 

   1.1 주요 기능

      - 데이터베이스 스키마 변경 사항을 버전 관리
      - 자동 및 수동 마이그레이션 스크립트 생성
      - 다중 환경 지원
      - 롤백 및 업그레이드 기능 제공

 

2. Alembic 설치

pip install alembic

 

3. Alembic 설정 및 초기화

   3.1 프로젝트에 Alembic 초기화

   - 이 명령을 실행하면 alembic 폴더와 alembic.ini 설정 파일이 생성된다.

alembic init alembic

 

   3.2 설정 파일 수정 (alembic.ini)

      - sqlalchemy.url 값을 프로젝트의 데이터베이스 URL로 변경한다.

sqlalchemy.url = postgresql://user:password@localhost/dbname

 

   3.3 환경 파일 설정 (alembic/env.py)

      - target_metadata를 SQLAlchemy의 Base와 연결해야 한다.

from myapp.models import Base

target_metadata = Base.metadata

 

4. 마이그레이션 관리

   4.1 마이그레이션 스크립트 생성

      - 이 명령을 실행하면 alembic/versions 폴더에 새로운 마이그레이션 파일이 생성 된다.

alembic revision -m "Create users table"

 

   4.2 마이그레이션 스크립트 작성

      - 자동 생성된 마이그레이션 파일을 열고 upgrade와 downgrade 함수를 작성한다.

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'users',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('name', sa.String(50), nullable=False),
        sa.Column('email', sa.String(100), unique=True, nullable=False)
    )

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

 

   4.3 마이그레이션 적용

      - head는 최신 버전으로 마이그레이션을 적용하는 것을 의미한다.

alembic upgrade head

 

   4.4 마이그레이션 롤백

      - -1은 한 단계 이전 버전으로 되돌리는 것을 의미한다.

alembic downgrade -1

 

5. 자동 마이그레이션 생성

   - SQLAlchemy 모델의 변경 사항을 감지하여 자동으로 마이그레이션 스크립트를 생성할 수 있다.

   - 이후, 생성된 마이그레이션 파일을 확인한 후 alembic upgrade head로 적용한다

alembic revision --autogenerate -m "Auto migration"

 

6. 특정 버전으로 이동

   - revision_id는 alembic history 명령어를 통해 확인할 수 있습니다.

alembic downgrade <revision_id>

 

   - 또는

alembic upgrade <revision_id>

 

7. Alembic 주요 명령어 요약

명령어 설명
alembic init alembic Alembic 초기화
alembic revision -m "메시지" 새 마이그레이션 파일 생성
alembic revision --autogenerate -m "메시지" 자동 마이그레이션 생성
alembic upgrade head 최신 마이그레이션 적용
alembic downgrade -1 한 단계 이전으로 롤백
alembic history 마이그레이션 히스토리 확인
alembic current 현재 적용된 마이그레이션 확인

 

8.  주의사항

   - Base.metadata.create_all(bind=engine) 를 사용하지 말고 처음부터 테이블을 alembic으로 만들자.

 

 

- reference : 

https://alembic.sqlalchemy.org/en/latest/

 

Welcome to Alembic’s documentation! — Alembic 1.14.1 documentation

Contents

alembic.sqlalchemy.org

https://puddingcamp.com/page/c2231b62-2fd4-4df9-b79b-ae3995955e05

 

Alembic 설정

## Alembic 마이그레이션 설정### (1) SQLAlchemy ORM 모델 인식Alembic 마이그레이션의 대상을 지정 설정과 마이그레이션을 실행하는 함수는 `alembic` 디렉터리에 있는 `env.py` 파일에 있어요. 우리는 SQLModel

puddingcamp.com

https://storyofvector7.tistory.com/80

 

[SQLAlchemy] Alembic을 이용해서 DB버전관리를 해보자

DJango에서는 기본적으로 DB마이그레이션 기능이 존재합니다. python manage.py makemigrationsmakemigrations 명령어로 DB변경 내역을 파이썬 파일로 자동 작성하고python manage.py migratemigrate 명령어를 사용해서

storyofvector7.tistory.com

https://velog.io/@osj1405/FastAPI-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B2%A0%EC%9D%B4%EC%8A%A4-%EC%97%B0%EA%B2%B0

 

[FastAPI] 데이터베이스 연결

SQLModel 구조와 기능 테이블 데이터베이스에 저장된 데이터를 가지고 있는 객체다. SQLModel을 사용해서 테이블을 생성하려면 테이블 모델 클래스를 먼저 정의해야 한다. pydantic 모델처럼 테이블을

velog.io

 

댓글