toolbase.py
changeset 2 efee419b7a2d
child 5 57cf8fdff5ed
equal deleted inserted replaced
0:eaae9539e910 2:efee419b7a2d
       
     1 import argparse
       
     2 
       
     3 from pgtools import pgmanager
       
     4 from common import config
       
     5 
       
     6 
       
     7 class ToolBase:
       
     8     def __init__(self, name, desc):
       
     9         self.parser = argparse.ArgumentParser(description=desc)
       
    10         self.parser.add_argument('target', metavar='target', type=str, help='Target database')
       
    11         
       
    12         self.config = config.ConfigParser()
       
    13         self.config.add_argument('databases', type=dict)
       
    14         self.config.add_argument('meta_db')
       
    15         self.config.add_argument('meta_query')
       
    16         
       
    17         self.pgm = pgmanager.get_instance()
       
    18         
       
    19     def init(self):
       
    20         self.config.load('pgtoolkit.conf')
       
    21         self.args = self.parser.parse_args()
       
    22         
       
    23         if self.config.meta_db:
       
    24             self.pgm.create_conn(name='meta', dsn=self.config.meta_db)
       
    25             self.buildconn('target', self.args.target)
       
    26             self.pgm.close_conn('meta')
       
    27 
       
    28     def buildconn(self, name, targetname):
       
    29         with self.pgm.cursor('meta') as curs:
       
    30             curs.execute(self.config.meta_query, [targetname])
       
    31             row = curs.fetchone_dict()
       
    32             curs.connection.commit()
       
    33             
       
    34             if not row:
       
    35                 raise Exception('Unknown database "%s"' % targetname)
       
    36             
       
    37             self.pgm.create_conn(name=name, **row)
       
    38