Symfony4/5 lock table for critical doctrine transactions

I have a relatively critical script on a controller action.

It creates a new entity and sets a rank if none is defined.
For this logic I count all related entities which created at the time and then I count the highest number plus one. That’s it.

But because I send 10 requests at the same time there are duplicates which I want to prevent.

But locking seems not to be working.

enter image description here

And this is the controller action:

public function addPolygonToRoute(Request $request, RoutePolygonRepository $routePolygonRepository, Route $entity)
{
    $this->denyAccessUnlessGranted(RouteVoter::EDIT, $entity);

    /** @var DoctrineDBALConnection $conn */
    $conn = $this->getDoctrine()->getConnection();
    $conn->beginTransaction();

    $routePolygon = new RoutePolygon();
    $routePolygon->setRoute($entity);

    $form = $this->createForm(RoutePolygonType::class, $routePolygon);
    $form->submit($request->request->all(), true);

    if ($form->isSubmitted() && $form->isValid())
    {
        if ($foundRoutePolygon = $routePolygonRepository->findOneBy([
            'polygon' => $routePolygon->getPolygon(),
            'route' => $routePolygon->getRoute()
        ])) {
            if (null !== $routePolygon->getRank())
            {
                $foundRoutePolygon->setRank($routePolygon->getRank());
            }
            $routePolygon = $foundRoutePolygon;
        }

        if(null === $routePolygon->getRank())
        {
            $routePolygon->setRank(max($entity->getRoutePolygons()->map(function(RoutePolygon $routePolygon) {
                    return $routePolygon->getRank();
                })->toArray() + [0]) + 1);
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($routePolygon);
        $em->flush();

        $conn->commit();
        return $routePolygon;
    }

    $conn->commit();

    return $this->view($this->getErrorsView($form->getErrors(true, true)), Response::HTTP_BAD_REQUEST);
}

Depending on the requests it works sometimes but when Symfony handles 2 requests at the same time the counting isn’t working.

1 -> 2 2 2 -> 3 -> 4 -> 5 5

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *