@contextmanager
def queries_captured(include_savepoints=False):
 queries = []
 def wrapper_execute(self, action, sql, params=()):
  start = time.time()
  try:
   return action(sql, params)
  finally:
   stop = time.time()
   duration = (stop - start)
   if (include_savepoints or ('SAVEPOINT' not in sql)):
    queries.append({'sql': self.mogrify(sql, params).decode('utf-8'), 'time': ('%.3f' % duration)})
 old_execute = TimeTrackingCursor.execute
 old_executemany = TimeTrackingCursor.executemany
 def cursor_execute(self, sql, params=()):
  return wrapper_execute(self, super(TimeTrackingCursor, self).execute, sql, params)
 TimeTrackingCursor.execute = cursor_execute
 def cursor_executemany(self, sql, params=()):
  return wrapper_execute(self, super(TimeTrackingCursor, self).executemany, sql, params)
 TimeTrackingCursor.executemany = cursor_executemany
 (yield queries)
 TimeTrackingCursor.execute = old_execute
 TimeTrackingCursor.executemany = old_executemany

@ contextmanager def queries_captured ( include_savepoints = False ) : queries = [ ] def wrapper_execute ( self , action , sql , params = ( ) ) : start = time . time ( ) try : return action ( sql , params ) finally : stop = time . time ( ) duration = ( stop - start ) if ( include_savepoints or ( 'SAVEPOINT' not in sql ) ) : queries . append ( { 'sql' : self . mogrify ( sql , params ) . decode ( 'utf-8' ) , 'time' : ( '%.3f' % duration ) } ) old_execute = TimeTrackingCursor . execute old_executemany = TimeTrackingCursor . executemany def cursor_execute ( self , sql , params = ( ) ) : return wrapper_execute ( self , super ( TimeTrackingCursor , self ) . execute , sql , params ) TimeTrackingCursor . execute = cursor_execute def cursor_executemany ( self , sql , params = ( ) ) : return wrapper_execute ( self , super ( TimeTrackingCursor , self ) . executemany , sql , params ) TimeTrackingCursor . executemany = cursor_executemany ( yield queries ) TimeTrackingCursor . execute = old_execute TimeTrackingCursor . executemany = old_executemany
allow a user to capture just the queries executed during the with statement .