Coroutine was not awaited error when running command.stamp() in async dialect #1515
-
Describe the bug Expected behavior async def setup_db_engine() -> async_sessionmaker | None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
alembic_cfg = Config("alembic.ini")
command.stamp(alembic_cfg, "head")
return async_sessionmaker(engine, expire_on_commit=False) To Reproduce from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
class Base(DeclarativeBase, MappedAsDataclass):
pass
class MyModel(Base):
__tablename__ = "my_model"
# Attributes
id: Mapped[int] = mapped_column(init=False, primary_key=True)
name: Mapped[str] Generate config.set_main_option("sqlalchemy.url", <my_connection_string>) Call setup_db_engine() above: async def main():
session = await setup_db_engine() Error
Versions.
Additional Context async def run_async_migrations() -> None:
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online() I believe the error here is because Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
Hi, You will need to modify your code to conditionally use asyncio.run or the existing loop to run the def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
try:
asyncio.get_running_loop().run_until_complete(run_async_migrations())
return
except RuntimeError:
pass
asyncio.run(run_async_migrations()) |
Beta Was this translation helpful? Give feedback.
-
IIRC it's not the first time we get this request. Overall we could have a cookbook example for this. Doing the proper thing also works but it may not be as clear to read. We can check what it would look like |
Beta Was this translation helpful? Give feedback.
Hi,
You will need to modify your code to conditionally use asyncio.run or the existing loop to run the
run_async_migrations
coroutine.something like this could work