Migracje bazy danych za pomocą Alembic
Bezpiecznie rozwijaj schemat SQLAlchemy w czasie za pomocą Alembic: inicjalizuj migracje, automatycznie generuj rewizje oraz stosuj lub wycofuj zmiany w projekcie FastAPI.
Migracje bazy danych za pomocą Alembic to bezpłatna lekcja FastAPI Backend Development Bootcamp na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej FastAPI Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Często zadawane pytania
Czy lekcja „Migracje bazy danych za pomocą Alembic” jest bezpłatna?
Tak — pełny tekst „Migracje bazy danych za pomocą Alembic” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu FastAPI Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.
Co nauczysz się w „Migracje bazy danych za pomocą Alembic”?
Bezpiecznie rozwijaj schemat SQLAlchemy w czasie za pomocą Alembic: inicjalizuj migracje, automatycznie generuj rewizje oraz stosuj lub wycofuj zmiany w projekcie FastAPI. Ćwiczysz FastAPI Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć FastAPI Backend Development Bootcamp?
Nie wymagamy żadnego doświadczenia. FastAPI Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Migracje bazy danych za pomocą Alembic”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji FastAPI Backend Development Bootcamp?
Tak. Każda lekcja FastAPI Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Podstawy ORM SQLAlchemy
- Łączenie FastAPI z PostgreSQL
- Operacje CRUD z SQLAlchemy
- Migracje bazy danych za pomocą Alembic