0Pricing
FastAPI Backend Development Bootcamp · 강의

Alembic을 활용한 데이터베이스 마이그레이션

Alembic을 사용해 시간에 따라 SQLAlchemy 스키마를 안전하게 발전시킵니다. 마이그레이션을 초기화하고 수정본을 자동 생성하며 변경 사항을 적용하거나 되돌립니다.

Alembic을 활용한 데이터베이스 마이그레이션은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Migrations

Your database schema changes as your app grows: new columns, tables, and indexes. Migrations are versioned, repeatable scripts that evolve the schema without losing data. Alembic is the standard tool for SQLAlchemy.

create_all Is Not Enough

Base.metadata.create_all() creates missing tables but never alters existing ones. It cannot add a column to a populated table or track history. Production needs real migrations.

Installing and Initializing

Install Alembic and scaffold its folder. This creates an alembic/ directory and alembic.ini.

pip install alembic
alembic init alembic

Pointing Alembic at Your Models

In alembic/env.py, set target_metadata to your SQLAlchemy Base.metadata so autogenerate can compare models to the live schema.

from app.database import Base
from app import models  # ensure models are imported

target_metadata = Base.metadata

Setting the Database URL

Configure the connection string. Reading it from an env var keeps secrets out of source control.

import os
config.set_main_option('sqlalchemy.url', os.environ['DATABASE_URL'])

Autogenerating a Revision

Alembic compares your models to the database and writes a migration script with the differences.

alembic revision --autogenerate -m 'add email to users'

Anatomy of a Migration

Each script has upgrade() and downgrade(). Upgrade applies the change; downgrade reverses it. Always review autogenerated code before running it.

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

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

Applying Migrations

Run upgrade head to apply all pending migrations up to the latest revision.

alembic upgrade head

Rolling Back

Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.

alembic downgrade -1

Revision Chain Mental Model

Migrations form a linked list: each revision records its down_revision. Alembic walks the chain to know what to apply. Here is the idea in plain Python.

revisions = [
    {'id': 'a1', 'down': None},
    {'id': 'b2', 'down': 'a1'},
    {'id': 'c3', 'down': 'b2'},
]
order = []
cur = 'c3'
by_id = {r['id']: r for r in revisions}
while cur:
    order.append(cur)
    cur = by_id[cur]['down']
print(list(reversed(order)))

Migration Best Practices

Keep migrations safe:

  • Review autogenerated scripts; they miss some changes (e.g. column renames).
  • Run migrations in CI/CD before deploying code.
  • Make additive changes first, remove old columns in a later release.
  • Never edit an already-applied migration; create a new one.

Quick Check

Why is Base.metadata.create_all() insufficient for evolving a production schema?

Recap

You added safe schema evolution:

  • Initialized Alembic and wired it to your models and DB URL.
  • Autogenerated revisions with upgrade() / downgrade().
  • Applied with upgrade head and reverted with downgrade.
  • Followed best practices for reviewing and sequencing migrations.

자주 묻는 질문

“Alembic을 활용한 데이터베이스 마이그레이션” 강의는 무료인가요?

네 — “Alembic을 활용한 데이터베이스 마이그레이션” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“Alembic을 활용한 데이터베이스 마이그레이션”에서 뭘 배우나요?

Alembic을 사용해 시간에 따라 SQLAlchemy 스키마를 안전하게 발전시킵니다. 마이그레이션을 초기화하고 수정본을 자동 생성하며 변경 사항을 적용하거나 되돌립니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“Alembic을 활용한 데이터베이스 마이그레이션” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. SQLAlchemy ORM 기초
  2. FastAPI와 PostgreSQL 연결
  3. SQLAlchemy를 활용한 CRUD 작업
  4. Alembic을 활용한 데이터베이스 마이그레이션
← FastAPI Backend Development Bootcamp(으)로 돌아가기