Write database migrations using Alembic programmatically. Detect the current revision, generate a new migration script based on the difference between SQLAlchemy models and the DB, and apply the upgrade.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This details using Alembic's Python API to detect the current DB revision, autogenerate a new migration by comparing models to the DB, and apply the upgrade—all requiring target_metadata set in config attributes and a properly configured env.py to enable autogeneration.
You don’t have to shell out to alembic to drive it, the package exposes the same entry points the CLI uses.
The only two prerequisites are:
a normal alembic.ini and env.py somewhere on disk, and
a place to get at your model metadata so that autogenerate can diff it against the live schema.
A minimal env.py that honours target_metadata from the Config attributes looks like this:
python
# migrations/env.py
from alembic import context
from logging.config import fileConfig
config = context.config
fileConfig(config.config_file_name)
# alembic.command.revision will put Base.metadata into config.attributes
target_metadata = config.attributes.get("target_metadata")
def run_migrations_online():
url = config.get_main_option("sqlalchemy.url")
engine = create_engine(url)
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True, # include type changes
)
with context.begin_transaction():
context.run_migrations()
run_migrations_online()
With that in place you can drive Alembic from your own code:
python
from alembic import command
from alembic.config import Config
from alembic.migration import MigrationContext
from sqlalchemy import create_engine
from myapp.models import Base # your declarative base
# build the alembic configuration and pass metadata for autogenerate
cfg = Config("alembic.ini")
cfg.set_main_option("script_location", "migrations")
cfg.attributes["target_metadata"] = Base.metadata
# connect to the database
engine = create_engine(cfg.get_main_option("sqlalchemy.url"))
# detect the current revision in the database
with engine.connect() as conn:
ctx = MigrationContext.configure(conn)
current_rev = ctx.get_current_revision()
print(f"Current revision: {current_rev}")
# create a new revision file based on model/db differences
command.revision(cfg, message="autogenerated", autogenerate=True)
# apply the upgrade to the latest (head) revision
command.upgrade(cfg, "head")
The call to revision(..., autogenerate=True) will invoke the env.py, compare Base.metadata against the connected database, and write a new migration script under migrations/versions. The subsequent upgrade applies it. If you don’t want to use alembic.ini, you can set sqlalchemy.url and script_location directly on the Config instance instead of reading a file.