Skip to content

Commit 34c8acf

Browse files
committed
Ensure proper handling of asyncio event loops and dispose SQLAlchemy engines.
1 parent cde7681 commit 34c8acf

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/migrations/env.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import asyncio
12
import hashlib
23
import importlib
34
import logging
45
import sys
5-
from asyncio import get_event_loop
66
from datetime import datetime
77
from os import listdir, path
88
from os.path import isfile, join
@@ -423,15 +423,18 @@ def migration_callable(*args, **kwargs):
423423
await rec["connection"].close()
424424
else:
425425
rec["connection"].close()
426+
# Dispose all engines to prevent hanging connections
427+
sa_manager.dispose_engines()
426428

427429

428430
background_tasks = set()
429431

430432
if context.is_offline_mode():
431433
run_migrations_offline()
432434
else:
433-
loop = get_event_loop()
434-
if loop.is_running():
435+
try:
436+
loop = asyncio.get_running_loop()
437+
# We're already in an event loop (e.g., running in async context)
435438
task = loop.create_task(run_migrations_online())
436439
# Add task to the set. This creates a strong reference.
437440
background_tasks.add(task)
@@ -440,5 +443,6 @@ def migration_callable(*args, **kwargs):
440443
# make each task remove its own reference from the set after
441444
# completion:
442445
task.add_done_callback(background_tasks.discard)
443-
else:
444-
loop.run_until_complete(run_migrations_online())
446+
except RuntimeError:
447+
# No event loop is running, so we need to create one
448+
asyncio.run(run_migrations_online())

0 commit comments

Comments
 (0)