Programmatic upgrade using async db driver #991
Answered
by
zzzeek
alejoar
asked this question in
Usage Questions
-
I want my app to auto upgrade the db every time it starts up. For that I followed instructions provided by @zzzeek here: #805 (although to be fair I'm not sure I followed properly) I created a minimal example with my issue here: https://github.com/alejoar/fastapi-async-sqlalchemy-alembic These work (from the cli):
This doesn't work (from the code):In
In (this runs on app start up)
|
Beta Was this translation helpful? Give feedback.
Answered by
zzzeek
Feb 15, 2022
Replies: 1 comment 10 replies
-
Place this function in your env.py script: def run_migrations_online():
connectable = config.attributes.get('connection', None)
if connectable is None:
# only create Engine if we don't have a Connection
# from the outside
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
else:
context.configure(
connection=connectable,
target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations() then run this script as follows: import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
from alembic import command, config
def run_upgrade(connection, cfg):
cfg.attributes["connection"] = connection
command.upgrade(cfg, "head")
async def run_async_upgrade():
async_engine = create_async_engine("sqlite+aiosqlite://", echo=True)
async with async_engine.begin() as conn:
await conn.run_sync(run_upgrade, config.Config("alembic.ini"))
asyncio.run(run_async_upgrade()) for the flask part, you'd need to ask flask people for that. |
Beta Was this translation helpful? Give feedback.
10 replies
Answer selected by
alejoar
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Place this function in your env.py script: