Migrations
A migration is a versioned, repeatable change to a database schema (and sometimes to data). Alembic and Django migrations are the two common Python tools. create_all is not a migration strategy.
Detailed Explanation
A model change is not a database change until you generate SQL and apply it. Migrations store that SQL (or a Python description of it) in a chain of files. Each environment — laptop, CI, production — applies the same chain. The database records which revisions it has seen (alembic_version, django_migrations).
Django: makemigrations writes a file, migrate applies it. You review the file. Autodetector is good at add-column and bad at renames (it may drop and add). SeparateDatabaseAndState and RunPython exist for data moves.
Alembic: revision --autogenerate diffs the SQLAlchemy metadata to the database and writes a script with upgrade and downgrade. Autogenerate misses some constraints and all data migrations. Read the script. upgrade head applies. Expand/contract: add a column nullable, backfill, then constrain, so you can deploy code that works with both schemas.
Zero-downtime rules: do not drop a column the old app still reads. Do not add a non-null column without a default in one step if the old app writes rows. Split "expand" and "contract" deploys.
Never apply unreviewed autogenerate on production. Never rewrite a migration that has already run on a shared database; add a new revision. Never run migrate against production from a laptop as a habit; use the same pipeline as the app deploy.
Base.metadata.create_all builds empty tables for a demo. It will not alter a live table. Tests can use create_all on sqlite; production cannot.
Code Examples
# Alembic-shaped revision (sketch)
def upgrade() -> None:
# op.add_column("orders", sa.Column("currency", sa.String(3), server_default="USD"))
pass
def downgrade() -> None:
# op.drop_column("orders", "currency")
pass# Django data migration sketch
def forwards(apps, schema_editor):
Order = apps.get_model("shop", "Order")
Order.objects.filter(currency="").update(currency="USD")Common Gotchas
Autogenerate rename as drop+add
you lose the column data. Write a rename operation by hand.
Non-null column on a table with rows, no default
the migration fails or locks the table. Two-step it.
Editing an applied revision
other machines have the old file. New revision only.
`create_all` is for tests and first-time demos
it is not how you evolve production.