tortoise / aerich

A database migrations tool for TortoiseORM, ready to production.
https://github.com/tortoise/aerich
Apache License 2.0
843 stars 96 forks source link

RuntimeError: attached to a different loop #103

Closed oceannw closed 3 years ago

oceannw commented 3 years ago

aerich: 2.0 - 4.4 tortoise-orm: 0.16.15 - 0.16.18 Sanic: 20.6.3 - 20.6

I tested the migrate function under the above various configurations, but there are always exceptions:

RuntimeError: Task <Task pending coro=<migrate() running at env/lib/python3.7/site-packages/aerich/cli.py:94> cb=[run_until_complete.<locals>.<lambda>()]> got Future <Task pending coro=<Pool._wakeup() running at env/lib/python3.7/site-packages/aiomysql/pool.py:188>> attached to a different loop

I find that migrate is running in the uvloop.Loop, and aiomysql is running in the _UnixSelectorEventLoop. so, I just remove the code in sanic.server.py or add the code in aerich.cli.py at line 30, it's all fine.

try:
    import uvloop  # type: ignore

    if not isinstance(asyncio.get_event_loop_policy(), uvloop.EventLoopPolicy):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
    pass

I hope to get a way to fix it, thx.

long2ice commented 3 years ago

aerich doesn't depends on uvloop, it just read config from your project and run it's own loop, maybe you should confirm not run a new loop when exec aerich command.

oceannw commented 3 years ago

I try that aerich 1.9 is ok and From 2.0 to the latest version will throw the error.

I find that cli.py(line:94) will get _UnixSelectorEventLoop at first, and get uvloop.Loop when throw the error later. Maybe some function of aerich called Sanic, and Sanic have configure a new loop.

And now, I have solved this problem, but others may encounter the same situation in the future. Therefore, it is recommended to add a way configure the loop.

At the end , I think the issue can be close, thx!