Alembicによるデータベースマイグレーション
Alembicを使ってSQLAlchemyのスキーマを安全に発展させます。FastAPIプロジェクトでマイグレーションを初期化し、リビジョンを自動生成し、変更を適用・ロールバックします。
「Alembicによるデータベースマイグレーション」はCoddyKit上の無料FastAPI Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 alembicPointing 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.metadataSetting 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 headRolling Back
Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.
alembic downgrade -1Revision 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 headand reverted withdowngrade. - Followed best practices for reviewing and sequencing migrations.
よくある質問
「Alembicによるデータベースマイグレーション」レッスンは無料ですか?
はい。「Alembicによるデータベースマイグレーション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、FastAPI Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 FastAPI Backend Development Bootcampコースには全4レッスンが含まれています。
「Alembicによるデータベースマイグレーション」で何を学びますか?
Alembicを使ってSQLAlchemyのスキーマを安全に発展させます。FastAPIプロジェクトでマイグレーションを初期化し、リビジョンを自動生成し、変更を適用・ロールバックします。 ブラウザで直接実行するハンズオンコードでFastAPI Backend Development Bootcampを演習し、24時間対応の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フィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- SQLAlchemy ORMの基礎
- FastAPIとPostgreSQLの接続
- SQLAlchemyによるCRUD操作
- Alembicによるデータベースマイグレーション