From 1966367caf4100a65ab56412387924c7c414ca4e Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sun, 11 Sep 2022 12:33:28 +0200 Subject: [PATCH] Fixed ApiKeyRepository for MS and Postgres --- .../src/ApiKey/Repository/ApiKeyRepository.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/module/Rest/src/ApiKey/Repository/ApiKeyRepository.php b/module/Rest/src/ApiKey/Repository/ApiKeyRepository.php index 46c1e1a5..ec49145e 100644 --- a/module/Rest/src/ApiKey/Repository/ApiKeyRepository.php +++ b/module/Rest/src/ApiKey/Repository/ApiKeyRepository.php @@ -14,13 +14,16 @@ class ApiKeyRepository extends EntitySpecificationRepository implements ApiKeyRe { $em = $this->getEntityManager(); $em->wrapInTransaction(function () use ($apiKey, $em): void { - $amountOfApiKeys = $em->createQueryBuilder()->select('COUNT(a.id)') - ->from(ApiKey::class, 'a') - ->getQuery() - ->setLockMode(LockMode::PESSIMISTIC_WRITE) - ->getSingleScalarResult(); + // Ideally this would be a SELECT COUNT(...), but MsSQL and Postgres do not allow locking on aggregates + // Because of that we check if at least one result exists + $firstResult = $em->createQueryBuilder()->select('a.id') + ->from(ApiKey::class, 'a') + ->setMaxResults(1) + ->getQuery() + ->setLockMode(LockMode::PESSIMISTIC_WRITE) + ->getOneOrNullResult(); - if ($amountOfApiKeys === 0) { + if ($firstResult === null) { $em->persist(ApiKey::fromKey($apiKey)); $em->flush(); }