Added ?_trace=1 option to trace SQL

Currently just dumps all SQL statements out on the console.
This commit is contained in:
Simon Willison 2019-04-20 22:28:15 -07:00
commit 7d01ca34a1
3 changed files with 69 additions and 4 deletions

41
datasette/tracer.py Normal file
View file

@ -0,0 +1,41 @@
import asyncio
from contextlib import contextmanager
import time
tracers = {}
def get_task_id():
try:
loop = asyncio.get_event_loop()
except RuntimeError:
return None
return id(asyncio.Task.current_task(loop=loop))
@contextmanager
def trace(type, action):
task_id = get_task_id()
if task_id is None:
yield
return
tracer = tracers.get(task_id)
if tracer is None:
yield
return
begin = time.time()
yield
end = time.time()
tracer.append((type, action, begin, end, 1000 * (end - begin)))
@contextmanager
def capture_traces(tracer):
# tracer is a list
task_id = get_task_id()
if task_id is None:
yield
return
tracers[task_id] = tracer
yield
del tracers[task_id]