Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Async connection created callback #321

Description

@alicederyn

I need to issue a set of SQL commands at the start of each connection, e.g. to set up the search path. Currently it looks like this can only be done by subclassing Database and completely reimplementing its connection method to return a subclass of Connection that overrides __aenter__. Would it be acceptable to add something akin to Django's connection_created signal? Syntax might look like

@db.connection_created
async def set_search_path(connection):
  await connection.execute("set search_path = my_schema")

Activity

  1. alicederyn commented on Apr 5, 2021

    @alicederyn
    Author

    For reference, here is my subclass implementation:

    from databases.core import Connection as BasicConnection, Database as BasicDatabase
    
    class Connection(BasicConnection):
        def __init__(self, backend, init_fns) -> None:
            super().__init__(backend)
            self.init_fns = init_fns
    
        async def __aenter__(self):
            c = await super().__aenter__()
            for init_fn in self.init_fns:
                await init_fn(c)
            return c
    
    
    class Database(BasicDatabase):
        """Adds a connection_created decorator to encode/databases."""
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self._init_fns = []
    
        def connection_created(self, async_callback_fn):
            self._init_fns.append(async_callback_fn)
    
        def connection(self):
            """This method copies the underlying implementation wholesale. Calling it with super is
            unfortunately not an option as it has a hard-coded reference to its own Connection
            implementation."""
            if self._global_connection is not None:
                return self._global_connection
    
            try:
                return self._connection_context.get()
            except LookupError:
                connection = Connection(self._backend, self._init_fns)
                self._connection_context.set(connection)
                return connection
  2. locked and limited conversation to collaborators on Apr 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions