pgtoolkit/toolbase.py
author Radek Brich <radek.brich@devl.cz>
Wed, 28 Mar 2012 17:25:18 +0200
changeset 33 bd0beda49bcb
parent 31 c2e6e24b83d9
child 34 98c7809af415
permissions -rw-r--r--
PgManager: log connection name with queries. BatchUpdateTool: handle some possible exceptions and try reconnect to database.

import argparse
import logging

from pgtoolkit import pgmanager, config
from pgtoolkit.coloredformatter import ColoredFormatter
from pgtoolkit.highlight import highlight


class ConnectionInfoNotFound(Exception):    
    pass


class ToolBase:
    def __init__(self, name, desc):
        self.parser = argparse.ArgumentParser(description=desc)
        self.parser.add_argument('-d', dest='debug', action='store_true',
            help='Debug mode - print database queries.')
        
        self.config = config.ConfigParser()
        self.config.add_argument('databases', type=dict)
        self.config.add_argument('meta_db')
        self.config.add_argument('meta_query')
        
        self.pgm = pgmanager.get_instance()
        self.target_isolation_level = None
        
    def init(self):
        self.config.load('pgtoolkit.conf')
        self.args = self.parser.parse_args()
        self.init_logging()
    
    def init_logging(self):
        # logging
        handler = logging.StreamHandler()
        format = ColoredFormatter(highlight(1,7,0)+'%(asctime)s %(levelname)-5s'+highlight(0)+' %(message)s', '%H:%M:%S')
        handler.setFormatter(format)
        handler.setLevel(logging.DEBUG)
        self.log = logging.getLogger('main')
        self.log.addHandler(handler)
        self.log.setLevel(logging.DEBUG)
        
        if self.args.debug:
            handler = logging.StreamHandler()
            handler.setFormatter(format)
            handler.setLevel(logging.DEBUG)
            logger = logging.getLogger('pgmanager_sql')
            logger.addHandler(handler)
            logger.setLevel(logging.DEBUG)

    def prepare_conn_from_metadb(self, name, lookup_name):
        '''Create connection in pgmanager using meta DB.
        
        name -- Name for connection in pgmanager.
        lookup_name -- Name of connection in meta DB.
        
        '''
        with self.pgm.cursor('meta') as curs:
            curs.execute(self.config.meta_query, [lookup_name])
            row = curs.fetchone_dict()
            curs.connection.commit()
            if row:
                self.pgm.create_conn(name=name,
                    isolation_level=self.target_isolation_level,
                    **row)
                return True

    def prepare_conn_from_config(self, name, lookup_name):
        '''Create connection in pgmanager using info in config.databases.'''
        if self.config.databases:
            if lookup_name in self.config.databases:
                dsn = self.config.databases[lookup_name]
                self.pgm.create_conn(name=name,
                    isolation_level=self.target_isolation_level,
                    dsn=dsn)
                return True

    def prepare_conns_from_cmdline_args(self, *pgm_names):
        if self.config.meta_db:
            self.pgm.create_conn(name='meta', dsn=self.config.meta_db)
        
        for name in pgm_names:
            lookup_name = self.args.__dict__[name]
            found = self.prepare_conn_from_config(name, lookup_name)
            if not found and self.config.meta_db:
                found = self.prepare_conn_from_metadb(name, lookup_name)
            if not found:
                raise ConnectionInfoNotFound('Connection name "%s" not found in config nor in meta DB.' % lookup_name)
        
        if self.config.meta_db:
            self.pgm.close_conn('meta')


class SimpleTool(ToolBase):
    def __init__(self, name, desc):
        ToolBase.__init__(self, name, desc)        
        self.parser.add_argument('target', metavar='target', type=str, help='Target database')
      
    def init(self):
        ToolBase.init(self)
        self.prepare_conns_from_cmdline_args('target')


class SrcDstTool(ToolBase):
    def __init__(self, name, desc):
        ToolBase.__init__(self, name, desc)        
        self.parser.add_argument('src', metavar='source', type=str, help='Source database')
        self.parser.add_argument('dst', metavar='destination', type=str, help='Destination database')
      
    def init(self):
        ToolBase.init(self)
        self.prepare_conns_from_cmdline_args('src', 'dst')