Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate entry '...' for key 'PRIMARY' during the transaction

This one happened to me last night. I am quite familiar with the nature of the error but still I cannot figure out what could have caused it. I might have a hunch, but I am not sure. I'll begin with some basic app's info:

My app has 3 entities: Loan, SystemPage and TextPage. Whenever someone adds a loans, one or more system pages is being added to the DB. Basically, it goes something like this:

if ( $form->isValid()){
    $this->em->getConnection()->beginTransation();
    $this->em->persist($loan);
    $this->em->flush();

    while ($someCondition){
        $page = new SystemPage();
        //... Fill the necessary data into page
        $page->setObject($loan);
        $this->em->persist($page);
    }

    $this->em->flush();
    $this->em->getConnection()->commit();
}

Please ignore potential typos, I am writing this literally by remembering

Entity Loan is mapped to table loans and SystemPage is mapped (via inheritance mapping) to system_pages and base_pages. Both of later one have id field which is set to AUTO_INCREMENT.

My hunch: There is another table called text_pages. Given that text_pages and base_pages on one hand and system_pages and base_pages on another share IDs, I am thinking that it could easily cause this:

User1: Create BasePage, acquire autoincrement ID (value = 1)
User2: Create BasePage, acquire autoincrement ID (value = 1)
User1: Create TextPage, use the ID from step 1
User2: Create SystemPage, use the ID from step 2

Two problems with this theory:

  • Transactions. That's why I used them in the first place
  • In the time of error there was no other activity on app by another user

Important: After waiting for a minute, resubmitting passed OK.

Could this be some weird MySQL transaction isolation bug? Any hint would be greatly appreciated...

Edit:

Part of DB Schema:

enter image description here

Please ignore the columns names which are in Serbian language

like image 914
Jovan Perovic Avatar asked Oct 31 '22 20:10

Jovan Perovic


1 Answers

flush() operation flushes all changes in one single transaction, so you have redundant code here...

You didn't stated if you can reproduce this bug and it would be convenient if you can provide db schema.

like image 69
Nikola Svitlica Avatar answered Nov 02 '22 10:11

Nikola Svitlica