Fixed ApiKeyRepository for MS and Postgres

This commit is contained in:
Alejandro Celaya 2022-09-11 12:33:28 +02:00
parent eed7b6e565
commit 1966367caf

View File

@ -14,13 +14,16 @@ class ApiKeyRepository extends EntitySpecificationRepository implements ApiKeyRe
{ {
$em = $this->getEntityManager(); $em = $this->getEntityManager();
$em->wrapInTransaction(function () use ($apiKey, $em): void { $em->wrapInTransaction(function () use ($apiKey, $em): void {
$amountOfApiKeys = $em->createQueryBuilder()->select('COUNT(a.id)') // Ideally this would be a SELECT COUNT(...), but MsSQL and Postgres do not allow locking on aggregates
->from(ApiKey::class, 'a') // Because of that we check if at least one result exists
->getQuery() $firstResult = $em->createQueryBuilder()->select('a.id')
->setLockMode(LockMode::PESSIMISTIC_WRITE) ->from(ApiKey::class, 'a')
->getSingleScalarResult(); ->setMaxResults(1)
->getQuery()
->setLockMode(LockMode::PESSIMISTIC_WRITE)
->getOneOrNullResult();
if ($amountOfApiKeys === 0) { if ($firstResult === null) {
$em->persist(ApiKey::fromKey($apiKey)); $em->persist(ApiKey::fromKey($apiKey));
$em->flush(); $em->flush();
} }