motam
motam

Reputation: 747

Handle deadlock in django with corrupted savepoint

I have an unavoidable bulk_create deadlock in my code. I decided to handle this part inside an atomic block and re-issue transaction when deadlock happened. Something like this:

while True:
    try:
        with transaction.atomic():
            bulk_create_some_data()

        return
    except OperationalError:
        log_error()

        continue

But this causes error You can't execute queries until the end of the 'atomic' block. I checked history of statements of mysql and found that the savepoint has been corrupted as below log shows.

*************************** 1. row ***************************    
event_id: 1                                                                      
SQL_TEXT: set autocommit=0                                                                                                                                               
MESSAGE_TEXT: NULL                                                                                                                                                                                                                      
*************************** 2. row ***************************                                                                                                                   
event_id: 2                                                                                                                                                                 
SQL_TEXT: SAVEPOINT `s139836523404544_x2`                                                                                                                                
MESSAGE_TEXT: NULL                                                                    
*************************** 3. row ***************************
event_id: 3 
SQL_TEXT: INSERT INTO `Transaction` ... 
MESSAGE_TEXT: Deadlock found when trying to get lock; try restarting transaction                                                                                             
*************************** 4. row ***************************                                                                                                                   
event_id: 4                                                                                                                                                                 
SQL_TEXT: ROLLBACK TO SAVEPOINT `s139836523404544_x2`                                                                                                                    
MESSAGE_TEXT: SAVEPOINT s139836523404544_x2 does not exist 

I found this thread which explains corruption of a savepoint is possible, it is an old thread and I am not sure whether it is still valid or not. How can I manage scenario like this to prevent an unavoidable lock causes my program crash. I am using django 3.1 and mysql 8.0.

Upvotes: 1

Views: 323

Answers (0)

Related Questions