pgtoolkit/tools/analyzeall.py
changeset 104 d8ff52a0390f
parent 103 24e94a3da209
child 105 10551741f61f
equal deleted inserted replaced
103:24e94a3da209 104:d8ff52a0390f
     1 from pgtoolkit.toolbase import SimpleTool
       
     2 from pgtoolkit import pgbrowser
       
     3 
       
     4 
       
     5 class AnalyzeAllTool(SimpleTool):
       
     6 
       
     7     """
       
     8     Analyze/vacuum all tables in selected schemas.
       
     9 
       
    10     Partially emulates VACUUM ANALYZE VERBOSE query.
       
    11     But this program is more configurable, skips pg_catalog etc.
       
    12 
       
    13     """
       
    14 
       
    15     def __init__(self):
       
    16         SimpleTool.__init__(self, name='analyzeall')
       
    17         self.target_isolation_level = 'autocommit'
       
    18 
       
    19     def specify_args(self):
       
    20         SimpleTool.specify_args(self)
       
    21         self.parser.add_argument('-s', dest='schema', nargs='*', help='Schema filter')
       
    22         self.parser.add_argument('--vacuum', action='store_true', help='Call VACUUM ANALYZE')
       
    23         self.parser.add_argument('--vacuum-full', action='store_true', help='Call VACUUM FULL ANALYZE')
       
    24         self.parser.add_argument('--reindex', action='store_true', help='Call REINDEX TABLE')
       
    25 
       
    26     def main(self):
       
    27         browser = pgbrowser.PgBrowser(self.pgm.get_conn('target'))
       
    28 
       
    29         query_patterns = ['ANALYZE %s.%s;']
       
    30         if self.args.vacuum:
       
    31             query_patterns = ['VACUUM ANALYZE %s.%s;']
       
    32         if self.args.vacuum_full:
       
    33             query_patterns = ['VACUUM FULL ANALYZE %s.%s;']
       
    34         if self.args.reindex:
       
    35             query_patterns += ['REINDEX TABLE %s.%s;']
       
    36 
       
    37         schema_list = self.args.schema
       
    38         if not schema_list:
       
    39             schema_list = [schema['name'] for schema in browser.list_schemas() if not schema['system']]
       
    40 
       
    41         for schema in schema_list:
       
    42             tables = browser.list_tables(schema=schema)
       
    43             with self.pgm.cursor('target') as curs:
       
    44                 for table in tables:
       
    45                     for query_pattern in query_patterns:
       
    46                         query = query_pattern % (schema, table['name'])
       
    47                         self.log.info(query)
       
    48                         curs.execute(query, [])
       
    49 
       
    50 
       
    51 cls = AnalyzeAllTool
       
    52