1+ import asyncio
12import hashlib
23import importlib
34import logging
45import sys
5- from asyncio import get_event_loop
66from datetime import datetime
77from os import listdir , path
88from 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
428430background_tasks = set ()
429431
430432if context .is_offline_mode ():
431433 run_migrations_offline ()
432434else :
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