33import dataclasses
44import inspect
55import typing as t
6+ from functools import partial
67from time import perf_counter
78
89import sqlalchemy as sa
@@ -65,15 +66,21 @@ class _QueryInfo:
6566 start_time : float
6667 end_time : float
6768 location : str
69+ bind_key : str | None
6870
6971 @property
7072 def duration (self ) -> float :
7173 return self .end_time - self .start_time
7274
7375
74- def _listen (engine : sa .engine .Engine ) -> None :
76+ def _listen (bind_key : str | None , engine : sa .engine .Engine ) -> None :
7577 sa_event .listen (engine , "before_cursor_execute" , _record_start , named = True )
76- sa_event .listen (engine , "after_cursor_execute" , _record_end , named = True )
78+ sa_event .listen (
79+ engine ,
80+ "after_cursor_execute" ,
81+ partial (_record_end , bind_key ),
82+ named = True ,
83+ )
7784
7885
7986def _record_start (context : sa .engine .ExecutionContext , ** kwargs : t .Any ) -> None :
@@ -83,7 +90,11 @@ def _record_start(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None:
8390 context ._fsa_start_time = perf_counter () # type: ignore[attr-defined]
8491
8592
86- def _record_end (context : sa .engine .ExecutionContext , ** kwargs : t .Any ) -> None :
93+ def _record_end (
94+ bind_key : str | None ,
95+ context : sa .engine .ExecutionContext ,
96+ ** kwargs : t .Any ,
97+ ) -> None :
8798 if not has_app_context ():
8899 return
89100
@@ -113,5 +124,6 @@ def _record_end(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None:
113124 start_time = context ._fsa_start_time , # type: ignore[attr-defined]
114125 end_time = perf_counter (),
115126 location = location ,
127+ bind_key = bind_key ,
116128 )
117129 )
0 commit comments