pgtools/pgstats.py
changeset 2 efee419b7a2d
equal deleted inserted replaced
0:eaae9539e910 2:efee419b7a2d
       
     1 # -*- coding: utf-8 -*-
       
     2 #
       
     3 # PgStats - browse database statistics
       
     4 #
       
     5 # Copyright (c) 2011  Radek Brich <radek.brich@devl.cz>
       
     6 #
       
     7 # Permission is hereby granted, free of charge, to any person obtaining a copy
       
     8 # of this software and associated documentation files (the "Software"), to deal
       
     9 # in the Software without restriction, including without limitation the rights
       
    10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
       
    11 # copies of the Software, and to permit persons to whom the Software is
       
    12 # furnished to do so, subject to the following conditions:
       
    13 #
       
    14 # The above copyright notice and this permission notice shall be included in
       
    15 # all copies or substantial portions of the Software.
       
    16 #
       
    17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
       
    18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
       
    19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
       
    20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
       
    21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
       
    22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
       
    23 # THE SOFTWARE.
       
    24 
       
    25 
       
    26 class PgStats:
       
    27     def __init__(self, conn=None):
       
    28         self.conn = conn
       
    29         
       
    30     def setconn(self, conn=None):
       
    31         self.conn = conn
       
    32 
       
    33     def _query(self, query, *args):
       
    34         try:
       
    35             curs = self.conn.cursor()
       
    36             curs.execute(query, args)
       
    37             curs.connection.commit()
       
    38             rows = curs.fetchall()
       
    39             return [dict(zip([desc[0] for desc in curs.description], row)) for row in rows]
       
    40         finally:
       
    41             curs.close()
       
    42 
       
    43     def list_long_queries(self, longer_than='1m'):
       
    44         return self._query('''SELECT datname, procpid, usename, current_query AS query,
       
    45             waiting, xact_start, query_start, backend_start
       
    46             FROM pg_stat_activity
       
    47             WHERE current_query <> '<IDLE>' AND query_start < now() - interval %s;''',
       
    48             longer_than)
       
    49