Skip to content

Commit

Permalink
Merge pull request #48 from IgelSchnauze/main
Browse files Browse the repository at this point in the history
Fix adding engines to `SQLAlchemyPanel` from `AsyncSession`
  • Loading branch information
mongkok authored May 4, 2024
2 parents 4311ef5 + 9139dcb commit 60fb7b1
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions debug_toolbar/panels/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from fastapi.dependencies.utils import solve_dependencies
from sqlalchemy import event
from sqlalchemy.engine import Connection, Engine, ExecutionContext
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session

from debug_toolbar.panels.sql import SQLPanel
Expand Down Expand Up @@ -40,7 +41,13 @@ def after_execute(self, context: ExecutionContext, **kwargs: t.Any) -> None:
}
self.add_query(str(context.engine.url), query)

async def add_engines(self, request: Request):
async def add_engines(self, request: Request): # noqa: C901
def add_bind_to_engines(bind: t.Union[Connection, Engine]):
if isinstance(bind, Connection):
self.engines.add(bind.engine)
else:
self.engines.add(bind)

route = request["route"]

if hasattr(route, "dependant"):
Expand All @@ -55,13 +62,16 @@ async def add_engines(self, request: Request):
pass
else:
for value in solved_result[0].values():
if isinstance(value, AsyncSession):
value = getattr(value, "sync_session", None)
if isinstance(value, Session):
bind = value.get_bind()

if isinstance(bind, Connection):
self.engines.add(bind.engine)
binds = getattr(value, "_Session__binds", None)
if binds:
for bind in binds.values():
add_bind_to_engines(bind)
else:
self.engines.add(bind)
bind = value.get_bind()
add_bind_to_engines(bind)

async def process_request(self, request: Request) -> Response:
await self.add_engines(request)
Expand Down

0 comments on commit 60fb7b1

Please sign in to comment.