Struggling with asynchronous database migrations in FastAPI using SQLAlchemy and Alembic
I'm sure I'm missing something obvious here, but I've spent hours debugging this and I need some guidance on I've searched everywhere and can't find a clear answer. Currently developing a FastAPI application that requires asynchronous database migrations using SQLAlchemy and Alembic. I've set up the basic structure for my FastAPI app and created several models that reflect my PostgreSQL database schema. The challenge arises when I attempt to perform migrations in an asynchronous context. While following the official Alembic documentation, I noticed that it primarily emphasizes synchronous operations, which leaves me in a bind for migrating my tables effectively. Hereβs a simplified version of my `env.py` file: ```python from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from alembic import context config = context.config # Create your asynchronous engine engine = create_async_engine('postgresql+asyncpg://user:password@localhost/dbname') async def run_migrations_online(): async with engine.connect() as connection: await connection.run_sync(context.configure) # This doesn't seem right context.run_migrations_online = run_migrations_online ``` When I execute `alembic upgrade head`, it throws an error: `TypeError: 'AsyncSession' object is not callable`. I attempted to resolve this by modifying the context configuration to include async functionality, but no luck yet. I even checked out a few GitHub repositories for example implementations but they only showcase synchronous setups. Would it be feasible to utilize a custom command that wraps the migration calls in an async function, or is there a more straightforward way to adapt Alembic to work with async SQLAlchemy sessions? Iβm keen to understand how others have approached async migrations in FastAPI and if there are specific best practices I should follow. For context: I'm using Python on Linux. What's the best practice here? I'm coming from a different tech stack and learning Python. I'm coming from a different tech stack and learning Python. Any advice would be much appreciated. The project is a REST API built with Python. Any advice would be much appreciated.