@@ -109,7 +109,11 @@ def __init__(self, database=None, *, loop=None):
109109
110110 self .loop = loop or asyncio .get_event_loop ()
111111 self .database = database or self .database
112- self .database .loop = self .loop
112+ attach_callback = getattr (self .database , 'attach_callback' , None )
113+ if attach_callback :
114+ attach_callback (lambda db : db .set_event_loop (self .loop ))
115+ else :
116+ self .database .set_event_loop (self .loop )
113117
114118 @property
115119 def is_connected (self ):
@@ -819,6 +823,22 @@ class AsyncDatabase:
819823 _async_wait = None # connection waiter
820824 _task_data = None # task context data
821825
826+ def set_event_loop (self , loop ):
827+ """Set event loop for the database. Usually, you don't need to
828+ call this directly. It's called from `Manager.connect()` or
829+ `.connect_async()` methods.
830+ """
831+ # These checks are not very pythonic, but I believe it's OK to be
832+ # a little paranoid about mismatching of asyncio event loops,
833+ # because such errors won't show clear traceback and could be
834+ # tricky to debug.
835+ loop = loop or asyncio .get_event_loop ()
836+ if not self .loop :
837+ self .loop = loop
838+ elif self .loop != loop :
839+ raise RuntimeError ("Error, the event loop is already set before. "
840+ "Make sure you're using the same event loop!" )
841+
822842 @asyncio .coroutine
823843 def connect_async (self , loop = None , timeout = None ):
824844 """Set up async connection on specified event loop or
@@ -833,7 +853,7 @@ def connect_async(self, loop=None, timeout=None):
833853 elif self ._async_wait :
834854 yield from self ._async_wait
835855 else :
836- self .loop = loop or asyncio . get_event_loop ( )
856+ self .set_event_loop ( loop )
837857 self ._async_wait = asyncio .Future (loop = self .loop )
838858
839859 conn = self ._async_conn_cls (
0 commit comments