title: Retry on deadlock for MySQL / SQLAlchemy
body: <p>I have searched for quite some time now and can't found a solution to my problem. We are using SQLAlchemy in conjunction with MySQL for our project and we encounter several time the dreaded error: </p>
  
  <blockquote>
    <p>1213, 'Deadlock found when trying to get lock; try restarting transaction'.</p>
  </blockquote>
  
  <p>We would like to try to restart the transaction at most three times in this case.</p>
  
  <p>I have started to write a decorator that does this but i don't know how to save the session state before the fail and retry the same transaction after it ? (As SQLAlchemy requires a rollback whenever an exception is raised)</p>
  
  <p>My work so far,</p>
  
  <pre><code>def retry_on_deadlock_decorator(func):
      lock_messages_error = ['Deadlock found', 'Lock wait timeout exceeded']
  
      @wraps(func)
      def wrapper(*args, **kwargs):
          attempt_count = 0
          while attempt_count &lt; settings.MAXIMUM_RETRY_ON_DEADLOCK:
              try:
                  return func(*args, **kwargs)
              except OperationalError as e:
                  if any(msg in e.message for msg in lock_messages_error) \
                          and attempt_count &lt;= settings.MAXIMUM_RETRY_ON_DEADLOCK:
                      logger.error('Deadlock detected. Trying sql transaction once more. Attempts count: %s'
                                   % (attempt_count + 1))
                  else:
                      raise
              attempt_count += 1
      return wrapper
  </code></pre>