|
1 #!/usr/bin/env python3.2 |
|
2 """ |
|
3 runquery |
|
4 |
|
5 Execute configured queries once. |
|
6 |
|
7 """ |
|
8 |
|
9 from pgtoolkit import toolbase, config |
|
10 |
|
11 import logging.handlers |
|
12 import time |
|
13 from datetime import datetime, timedelta |
|
14 |
|
15 |
|
16 class RunQueryTool(toolbase.ToolBase): |
|
17 def __init__(self): |
|
18 toolbase.ToolBase.__init__(self, name='runquery', desc='Run configured queries.') |
|
19 self.parser.add_argument('target', nargs='?', metavar='target', type=str, help='Target database') |
|
20 self.parser.add_argument('-c', dest='config', type=str, help='Additional config file (besides pgtoolkit.conf).') |
|
21 self.parser.add_argument('-q', dest='queries', metavar='QUERY', nargs='*', help='Queries to run.') |
|
22 |
|
23 self.config.add_argument('target', type=str, default=None) |
|
24 self.config.add_argument('queries', type=list, default=[]) |
|
25 self.config.add_argument('log_path', type=str) |
|
26 |
|
27 self.target_isolation_level = 'autocommit' |
|
28 |
|
29 self.init() |
|
30 |
|
31 def init(self): |
|
32 toolbase.ToolBase.init(self) |
|
33 if self.args.config: |
|
34 self.config.load(self.args.config) |
|
35 self.queries = self.args.queries or self.config.queries |
|
36 if self.config.log_path: |
|
37 self.init_file_logs(self.config.log_path) |
|
38 self.prepare_conns(target = self.args.target or self.config.target) |
|
39 |
|
40 def init_file_logs(self, path): |
|
41 format = logging.Formatter('%(asctime)s %(levelname)-5s %(message)s', '%y-%m-%d %H:%M:%S') |
|
42 handler = logging.handlers.TimedRotatingFileHandler(path+'/main.log', when='midnight', backupCount=5) |
|
43 handler.setFormatter(format) |
|
44 handler.setLevel(logging.DEBUG) |
|
45 logging.getLogger('main').addHandler(handler) |
|
46 |
|
47 format = logging.Formatter('%(asctime)s %(message)s', '%y-%m-%d %H:%M:%S') |
|
48 handler = logging.handlers.TimedRotatingFileHandler(path+'/pgnotices.log', when='midnight', backupCount=5) |
|
49 handler.setFormatter(format) |
|
50 handler.setLevel(logging.DEBUG) |
|
51 logging.getLogger('pgmanager_notices').addHandler(handler) |
|
52 |
|
53 def main(self): |
|
54 """Execute the queries.""" |
|
55 for q in self.queries: |
|
56 self.log.info('%s', q) |
|
57 with self.pgm.cursor('target') as curs: |
|
58 rows = curs.execute(q) |
|
59 self.log.info('Rows affected: %d', curs.rowcount) |
|
60 self.log.info('Result: %r', rows) |
|
61 self.log.info('Done') |
|
62 |
|
63 |
|
64 tool = RunQueryTool() |
|
65 tool.main() |
|
66 |