Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
import argparse
import logging
from pgtoolkit import pgmanager, config
from pgtoolkit.coloredformatter import ColoredFormatter
from pgtoolkit.highlight import highlight
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()
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')
logger.addHandler(handler)
def buildconn(self, name, lookup_name):
with self.pgm.cursor('meta') as curs:
curs.execute(self.config.meta_query, [lookup_name])
row = curs.fetchone_dict()
curs.connection.commit()
if not row:
raise Exception('Unknown database "%s"' % lookup_name)
self.pgm.create_conn(name=name, **row)
def prepareconns(self, *pgm_names):
# use meta db
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]
self.buildconn(name, lookup_name)
self.pgm.close_conn('meta')
# use config dict 'databases'
if self.config.databases:
for name in pgm_names:
lookup_name = self.args.__dict__[name]
dsn = self.config.databases[lookup_name]
self.pgm.create_conn(name=name, dsn=dsn)
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.prepareconns('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.prepareconns('src', 'dst')