batchupdate.py
changeset 33 bd0beda49bcb
parent 32 d59c473c9ad7
child 83 515fadd3d286
equal deleted inserted replaced
32:d59c473c9ad7 33:bd0beda49bcb
     2 
     2 
     3 import time
     3 import time
     4 
     4 
     5 from pgtoolkit import toolbase
     5 from pgtoolkit import toolbase
     6 from pgtoolkit.highlight import highlight
     6 from pgtoolkit.highlight import highlight
       
     7 from pgtoolkit.pgmanager import OperationalError
     7 
     8 
     8 
     9 
     9 class BatchUpdateTool(toolbase.SimpleTool):
    10 class BatchUpdateTool(toolbase.SimpleTool):
    10     def __init__(self):
    11     def __init__(self):
    11         toolbase.SimpleTool.__init__(self, name='batchupdate', desc='Run an UPDATE query until it does not update any rows.')
    12         toolbase.SimpleTool.__init__(self, name='batchupdate', desc='Run an UPDATE query until it does not update any rows.')
    13         self.parser.add_argument('--sleep', dest='sleep', default=0, type=int, help='Sleep SLEEP seconds between subsequent queries.')
    14         self.parser.add_argument('--sleep', dest='sleep', default=0, type=int, help='Sleep SLEEP seconds between subsequent queries.')
    14         self.init()
    15         self.init()
    15 
    16 
    16     def main(self):
    17     def main(self):
    17         # connect DB
    18         # connect DB
    18         with self.pgm.cursor('target') as curs:
    19         rowcount = 1
    19             rowcount = 1
    20         while rowcount > 0:
    20             while rowcount > 0:
    21             print('query:', self.args.query)
    21                 print('query:', self.args.query)
    22             with self.pgm.cursor('target') as curs:
    22                 curs.execute(self.args.query, [])
    23                 try:
    23                 rowcount = curs.rowcount
    24                     curs.execute(self.args.query, [])
    24                 print('updated', rowcount)
    25                     rowcount = curs.rowcount
    25                 curs.connection.commit()
    26                     print('updated', rowcount)
    26                 print('sleep %s seconds' % self.args.sleep)
    27                     curs.connection.commit()
    27                 time.sleep(self.args.sleep)
    28                 except (OperationalError, SystemError) as e:
       
    29                     print('Error:', str(e))
       
    30             print('sleep %s seconds' % self.args.sleep)
       
    31             time.sleep(self.args.sleep)
    28 
    32 
    29 
    33 
    30 tool = BatchUpdateTool()
    34 tool = BatchUpdateTool()
    31 tool.main()
    35 tool.main()
    32 
    36