반응형
다른 프로젝트도 같이 진행중인데 공부중이라 기존에 타 프로젝트에서 사용하는 테이블이 존재함.
마이그레이션 잘못했다가 테이블 여러번 날려먹을뻔하고 에러가 나서 다행이라고 생각함
drop...로그 보고 기절할뻔
1. migrations/env.py 수정하여 특정 테이블 무시
migrations/env.py
import os
from alembic import context
from sqlalchemy import create_engine, pool
from logging.config import fileConfig
from models import Base # models.py에서 모든 모델을 가져옴
# Alembic 설정 로드
config = context.config
fileConfig(config.config_file_name)
# 환경 변수에서 DATABASE_URL 가져오기
DATABASE_URL = os.getenv("DATABASE_URL")
connectable = create_engine(DATABASE_URL, poolclass=pool.NullPool)
# 무시할 테이블 리스트 정의
EXCLUDE_TABLES = {
"db_table",
"ex_db_table",
}
def include_object(object, name, type_, reflected, compare_to):
"""Alembic이 특정 테이블을 무시하도록 설정"""
if type_ == "table" and name in EXCLUDE_TABLES:
return False # 해당 테이블 무시
return True # 나머지는 처리
def run_migrations_online():
"""마이그레이션 실행 (데이터베이스 연결 포함)"""
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=Base.metadata,
include_object=include_object, # 무시할 테이블 적용
)
with context.begin_transaction():
context.run_migrations()
run_migrations_online()
- EXCLUDE_TABLES 리스트에 사용하지 않는 테이블 이름을 추가
- include_object 함수를 추가하여 Alembic이 특정 테이블을 무시하도록 설정
- context.configure()에서 include_object=include_object을 추가하여 적용
2. 새로운 마이그레이션 실행
📂 터미널에서 실행
# 잘못된 마이그레이션 롤백
alembic downgrade -1
# 새로운 마이그레이션 생성 (무시할 테이블 제외)
alembic revision --autogenerate -m "Exclude unused tables"
# 새로운 마이그레이션 적용
alembic upgrade head
# 최신 실행된 마이그레이션
alembic current
# 강제로 마이그레이션 실행
alembic stamp head
#마이그레이션 상태 확인(이전 마이그레이션들이 적용되었는지 확인)
alembic history --verbose
반응형
'Dev > Python' 카테고리의 다른 글
| 🚨[Alembic] 명령어 및 오류 설정확인 (0) | 2025.03.20 |
|---|---|
| [FastAPI] FastAPI+ Alembic 설정 및 프로세스 정리 (0) | 2025.03.19 |
| [Python] Code Formatter 코드포매터 (0) | 2025.03.17 |
| 🚨[Python] package import error (0) | 2025.03.15 |
| [Python] requirements.txt 생성 및 설치 방법 (0) | 2025.03.15 |