Guest User

Untitled

a guest
Apr 19th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. @contextmanager
  2. def transaction(connection):
  3. trans = connection.begin()
  4. try:
  5. yield trans
  6. except Exception:
  7. trans.rollback()
  8. raise
  9. else:
  10. trans.commit()
  11.  
  12.  
  13. def deadlock_first():
  14. import time
  15.  
  16. time.sleep(1)
  17. engine = sqlalchemy.create_engine('postgresql://{user}:{password}@{host}:{port}/{db}'.format(**config))
  18. connect = engine.connect()
  19. print(connect)
  20. sql = "select func1();"
  21. with transaction(connect) as trans:
  22. connect.execute(sql)
  23.  
  24.  
  25. def deadlock_retry():
  26. engine = sqlalchemy.create_engine('postgresql://{user}:{password}@{host}:{port}/{db}'.format(**config))
  27. connect = engine.connect()
  28. print(connect)
  29. sql = "select func2();"
  30. try:
  31. with transaction(connect) as trans:
  32. connect.execute(sql)
  33. except sqlalchemy.exc.OperationalError as e:
  34. if "deadlock" in str(e):
  35. with transaction(connect) as trans:
  36. connect.execute(sql)
  37.  
  38.  
  39. def main():
  40. t1 = threading.Thread(target=deadlock_first)
  41. t2 = threading.Thread(target=deadlock_retry)
  42. t1.start()
  43. t2.start()
Add Comment
Please, Sign In to add comment