toolbase.py
author Radek Brich <radek.brich@devl.cz>
Tue, 19 Jul 2011 14:36:33 +0200
changeset 3 1fe6c30f7700
parent 2 efee419b7a2d
child 5 57cf8fdff5ed
permissions -rw-r--r--
pgmanager: fix logging of queries

import argparse

from pgtools import pgmanager
from common import config


class ToolBase:
    def __init__(self, name, desc):
        self.parser = argparse.ArgumentParser(description=desc)
        self.parser.add_argument('target', metavar='target', type=str, help='Target database')
        
        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()
        
    def init(self):
        self.config.load('pgtoolkit.conf')
        self.args = self.parser.parse_args()
        
        if self.config.meta_db:
            self.pgm.create_conn(name='meta', dsn=self.config.meta_db)
            self.buildconn('target', self.args.target)
            self.pgm.close_conn('meta')

    def buildconn(self, name, targetname):
        with self.pgm.cursor('meta') as curs:
            curs.execute(self.config.meta_query, [targetname])
            row = curs.fetchone_dict()
            curs.connection.commit()
            
            if not row:
                raise Exception('Unknown database "%s"' % targetname)
            
            self.pgm.create_conn(name=name, **row)