timerproxy.py
59 lines
| 1.9 KiB
| text/x-python
|
PythonLexer
|
r49 | from sqlalchemy.interfaces import ConnectionProxy | ||
import time | ||||
r492 | from sqlalchemy import log | |||
r153 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = xrange(30, 38) | |||
def color_sql(sql): | ||||
COLOR_SEQ = "\033[1;%dm" | ||||
COLOR_SQL = YELLOW | ||||
normal = '\x1b[0m' | ||||
return COLOR_SEQ % COLOR_SQL + sql + normal | ||||
r172 | def one_space_trim(s): | |||
if s.find(" ") == -1: | ||||
return s | ||||
else: | ||||
s = s.replace(' ', ' ') | ||||
return one_space_trim(s) | ||||
r153 | def format_sql(sql): | |||
sql = color_sql(sql) | ||||
r172 | sql = sql.replace('\n', '') | |||
sql = one_space_trim(sql) | ||||
sql = sql\ | ||||
r494 | .replace(',', ',\n\t')\ | |||
r172 | .replace('SELECT', '\n\tSELECT \n\t')\ | |||
r236 | .replace('UPDATE', '\n\tUPDATE \n\t')\ | |||
.replace('DELETE', '\n\tDELETE \n\t')\ | ||||
r172 | .replace('FROM', '\n\tFROM')\ | |||
.replace('ORDER BY', '\n\tORDER BY')\ | ||||
.replace('LIMIT', '\n\tLIMIT')\ | ||||
.replace('WHERE', '\n\tWHERE')\ | ||||
.replace('AND', '\n\tAND')\ | ||||
.replace('LEFT', '\n\tLEFT')\ | ||||
.replace('INNER', '\n\tINNER')\ | ||||
.replace('INSERT', '\n\tINSERT')\ | ||||
.replace('DELETE', '\n\tDELETE') | ||||
r153 | return sql | |||
|
r49 | |||
class TimerProxy(ConnectionProxy): | ||||
r492 | ||||
def __init__(self): | ||||
super(TimerProxy, self).__init__() | ||||
self.logging_name = 'timerProxy' | ||||
self.log = log.instance_logger(self, True) | ||||
|
r49 | def cursor_execute(self, execute, cursor, statement, parameters, context, executemany): | ||
r492 | ||||
|
r49 | now = time.time() | ||
try: | ||||
r492 | self.log.info(">>>>> STARTING QUERY >>>>>") | |||
|
r49 | return execute(cursor, statement, parameters, context) | ||
finally: | ||||
total = time.time() - now | ||||
r90 | try: | |||
r492 | self.log.info(format_sql("Query: %s" % statement % parameters)) | |||
r90 | except TypeError: | |||
r492 | self.log.info(format_sql("Query: %s %s" % (statement, parameters))) | |||
self.log.info("<<<<< TOTAL TIME: %f <<<<<" % total) | ||||