FastAPI Backend Development Bootcamp · Lezione

Migrazioni del database con Alembic

Evolva in sicurezza lo schema SQLAlchemy nel tempo usando Alembic: inizializzi le migrazioni, generi automaticamente le revisioni e applichi o annulli le modifiche in un progetto FastAPI.

Lezione 4 di 413 passaggi

Migrazioni del database con Alembic è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.
Gratis per iniziare

Impara FastAPI Backend Development Bootcamp con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
21
Lezioni
84

Domande Frequenti

La lezione «Migrazioni del database con Alembic» è gratuita?

Sì — il testo completo di «Migrazioni del database con Alembic» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.

Cosa imparerò in «Migrazioni del database con Alembic»?

Evolva in sicurezza lo schema SQLAlchemy nel tempo usando Alembic: inizializzi le migrazioni, generi automaticamente le revisioni e applichi o annulli le modifiche in un progetto FastAPI. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?

Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Migrazioni del database con Alembic»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?

Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Fondamenti dell'ORM SQLAlchemy
  2. Collegare FastAPI a PostgreSQL
  3. Operazioni CRUD con SQLAlchemy
  4. Migrazioni del database con Alembic
← Torna a FastAPI Backend Development Bootcamp