Database Migration Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Database Migration runs in O(n) time and O(n) space, in Python as in every other language.
- ✓Alembic is the migration tool for SQLAlchemy: alembic revision --autogenerate diffs your models against the database and writes upgrade and downgrade functions built from op.add_column, op.create_index and op.execute.
- ✓Treat autogenerate as a first draft and read every line it produced, it detects added and dropped columns and indexes reliably, and it misses or mis-renders server defaults, type widenings, constraint changes and anything it cannot see in the models.
- ✓The Python trap: PostgreSQL cannot run CREATE INDEX CONCURRENTLY inside a transaction, and both tools wrap a migration in one by default.
- ✓On PostgreSQL 11 and later, adding a column with a non-volatile default is a catalogue-only change and is instant at any table size; before that it rewrote the whole table.
What Database Migration actually is
Database Migration in Python: what you actually reach for
Python implementation
from alembic import op
import sqlalchemy as sa
revision = "0042_add_last_seen"
down_revision = "0041_users_email_index"
def upgrade() -> None:
# PG11+: a non-volatile default is catalogue-only, instant on any size
op.add_column("users", sa.Column("last_seen_at", sa.DateTime(), server_default=sa.text("now()")))
# CREATE INDEX CONCURRENTLY cannot run inside a transaction
with op.get_context().autocommit_block():
op.create_index(
"ix_users_last_seen", "users", ["last_seen_at"], postgresql_concurrently=True
)
def downgrade() -> None:
with op.get_context().autocommit_block():
op.drop_index("ix_users_last_seen", postgresql_concurrently=True)
op.drop_column("users", "last_seen_at")Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Database Migration?
Alembic is the migration tool for SQLAlchemy: alembic revision --autogenerate diffs your models against the database and writes upgrade and downgrade functions built from op.add_column, op.create_index and op.execute. Django ships its own, with makemigrations, migrate, and RunPython for data changes alongside the schema operations.
What is the most common Python mistake when implementing Database Migration?
PostgreSQL cannot run CREATE INDEX CONCURRENTLY inside a transaction, and both tools wrap a migration in one by default. The migration fails with an explicit error, and the workaround is Alembic autocommit_block or Django atomic = False on the Migration class, but the deeper trap is what happens when you skip the CONCURRENTLY: a plain CREATE INDEX takes a lock that blocks writes to the table for as long as the build takes, which on a large table is a production incident rather than an error message.
How does Database Migration actually perform in Python?
On PostgreSQL 11 and later, adding a column with a non-volatile default is a catalogue-only change and is instant at any table size; before that it rewrote the whole table. Adding a NOT NULL constraint still scans the table unless you add it NOT VALID first and VALIDATE separately, which takes a weaker lock. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.