Search code examples
pythonsqlalchemyalembic

Alembic API how to get raw SQL script


My requirement is to generate a SQL script and upload that script to cloud storage. I'm using Alembic Command to generate SQL script.

command.upgrade(alembic_cfg, revision='a:b', sql=True)

The command.upgrade function prints the SQL script into the console. If multiple revisions are there then there will be multiple INFO logs.

Is there any way to store the raw SQL script to a variable?

raw_sql = command.upgrade(alembic_cfg, revision='a:b', sql=True)
upload_script(raw_sql)

I know can make use of the cli alembic upgrade head --sql > migration.sql


Solution

  • It seems like API is not available to achieve this. Finally, I have settled with the CLI command.

    upgrade = subprocess.run(['alembic', 'upgrade', upgrade_revision_range, '--sql'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    raw_sql = upgrade.stdout.decode('utf-8')