I am using SQLite as an application file format (see here for why you would want to do this) for my PySide-based desktop application. That is, when a user uses my app, their
See documentation of alembic.operations.base.Operations:
from alembic.runtime.migration import MigrationContext
from alembic.operations import Operations
conn = myengine.connect()
ctx = MigrationContext.configure(conn)
op = Operations(ctx)
op.alter_column("t", "c", nullable=True)
If you look at the commands API page from the alembic docs you see an example of how to run the CLI commands directly from a Python application. Without going through the CLI code.
Running alembic.config.main
has the downside that the env.py
script is executed which may not be what you want. For example, it will modify your logging config.
Another, very simple way is to use the "command API" linked above. For example, here is a small helper function which I ended up writing:
from alembic.config import Config
from alembic import command
def run_migrations(script_location: str, dsn: str) -> None:
LOG.info('Running DB migrations in %r on %r', script_location, dsn)
alembic_cfg = Config()
alembic_cfg.set_main_option('script_location', script_location)
alembic_cfg.set_main_option('sqlalchemy.url', dsn)
command.upgrade(alembic_cfg, 'head')
I am using the set_main_option
method here to be able to run the migrations on a different DB if needed. So I can simply call this as follows:
run_migrations('/path/to/migrations', 'postgresql:///my_database')
Where you get those two values (path and DSN) from is up to you. But this seems to be very close to what you want to achieve. The commands API also has the stamp() methods which allows you mark a given DB to be of a specific version. The example above can be easily adapted to call this.