pydbkit/tools/longqueries.py
changeset 104 d8ff52a0390f
parent 101 2a2d0d5df03b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pydbkit/tools/longqueries.py	Wed Jul 09 18:03:54 2014 +0200
@@ -0,0 +1,34 @@
+from pydbkit.toolbase import SimpleTool
+from pydbkit import pgstats
+from pycolib.ansicolor import highlight, YELLOW, BOLD
+
+
+class LongQueriesTool(SimpleTool):
+
+    """
+    List long running queries.
+    """
+
+    def __init__(self):
+        SimpleTool.__init__(self, name='longqueries')
+
+    def specify_args(self):
+        SimpleTool.specify_args(self)
+        self.parser.add_argument('--age', default='1m', help='How long must be the query running to be listed.')
+
+    def main(self):
+        stats = pgstats.PgStats(self.pgm.get_conn('target'))
+
+        for ln in stats.list_long_queries(self.args.age):
+            print(highlight(1),
+                  'backend PID: ', ln['procpid'],
+                  ', query_start: ', ln['query_start'].strftime('%F %T'),
+                  ', client IP: ', ln['client_addr'],
+                  ln['waiting'] and ', ' + highlight(1, YELLOW|BOLD) + 'waiting' or '',
+                  highlight(0), sep='')
+            print(ln['query'])
+            print()
+
+
+cls = LongQueriesTool
+