DefaultQueryCache.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\ORM\Cache;
  20. use Doctrine\Common\Collections\ArrayCollection;
  21. use Doctrine\Common\Proxy\Proxy;
  22. use Doctrine\ORM\Cache;
  23. use Doctrine\ORM\Cache\Logging\CacheLogger;
  24. use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
  25. use Doctrine\ORM\EntityManagerInterface;
  26. use Doctrine\ORM\Mapping\ClassMetadata;
  27. use Doctrine\ORM\PersistentCollection;
  28. use Doctrine\ORM\Query;
  29. use Doctrine\ORM\Query\ResultSetMapping;
  30. use Doctrine\ORM\UnitOfWork;
  31. use function array_key_exists;
  32. use function array_map;
  33. use function array_shift;
  34. use function array_unshift;
  35. use function assert;
  36. use function count;
  37. use function is_array;
  38. use function key;
  39. use function reset;
  40. /**
  41. * Default query cache implementation.
  42. */
  43. class DefaultQueryCache implements QueryCache
  44. {
  45. /** @var EntityManagerInterface */
  46. private $em;
  47. /** @var UnitOfWork */
  48. private $uow;
  49. /** @var Region */
  50. private $region;
  51. /** @var QueryCacheValidator */
  52. private $validator;
  53. /** @var CacheLogger */
  54. protected $cacheLogger;
  55. /** @var array<string,mixed> */
  56. private static $hints = [Query::HINT_CACHE_ENABLED => true];
  57. /**
  58. * @param EntityManagerInterface $em The entity manager.
  59. * @param Region $region The query region.
  60. */
  61. public function __construct(EntityManagerInterface $em, Region $region)
  62. {
  63. $cacheConfig = $em->getConfiguration()->getSecondLevelCacheConfiguration();
  64. $this->em = $em;
  65. $this->region = $region;
  66. $this->uow = $em->getUnitOfWork();
  67. $this->cacheLogger = $cacheConfig->getCacheLogger();
  68. $this->validator = $cacheConfig->getQueryValidator();
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [])
  74. {
  75. if (! ($key->cacheMode & Cache::MODE_GET)) {
  76. return null;
  77. }
  78. $cacheEntry = $this->region->get($key);
  79. if (! $cacheEntry instanceof QueryCacheEntry) {
  80. return null;
  81. }
  82. if (! $this->validator->isValid($key, $cacheEntry)) {
  83. $this->region->evict($key);
  84. return null;
  85. }
  86. $result = [];
  87. $entityName = reset($rsm->aliasMap);
  88. $hasRelation = ! empty($rsm->relationMap);
  89. $persister = $this->uow->getEntityPersister($entityName);
  90. assert($persister instanceof CachedEntityPersister);
  91. $region = $persister->getCacheRegion();
  92. $regionName = $region->getName();
  93. $cm = $this->em->getClassMetadata($entityName);
  94. $generateKeys = static function (array $entry) use ($cm): EntityCacheKey {
  95. return new EntityCacheKey($cm->rootEntityName, $entry['identifier']);
  96. };
  97. $cacheKeys = new CollectionCacheEntry(array_map($generateKeys, $cacheEntry->result));
  98. $entries = $region->getMultiple($cacheKeys) ?? [];
  99. // @TODO - move to cache hydration component
  100. foreach ($cacheEntry->result as $index => $entry) {
  101. $entityEntry = $entries[$index] ?? null;
  102. if (! $entityEntry instanceof EntityCacheEntry) {
  103. if ($this->cacheLogger !== null) {
  104. $this->cacheLogger->entityCacheMiss($regionName, $cacheKeys->identifiers[$index]);
  105. }
  106. return null;
  107. }
  108. if ($this->cacheLogger !== null) {
  109. $this->cacheLogger->entityCacheHit($regionName, $cacheKeys->identifiers[$index]);
  110. }
  111. if (! $hasRelation) {
  112. $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints);
  113. continue;
  114. }
  115. $data = $entityEntry->data;
  116. foreach ($entry['associations'] as $name => $assoc) {
  117. $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']);
  118. assert($assocPersister instanceof CachedEntityPersister);
  119. $assocRegion = $assocPersister->getCacheRegion();
  120. $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']);
  121. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  122. $assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']);
  123. $assocEntry = $assocRegion->get($assocKey);
  124. if ($assocEntry === null) {
  125. if ($this->cacheLogger !== null) {
  126. $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey);
  127. }
  128. $this->uow->hydrationComplete();
  129. return null;
  130. }
  131. $data[$name] = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints);
  132. if ($this->cacheLogger !== null) {
  133. $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKey);
  134. }
  135. continue;
  136. }
  137. if (! isset($assoc['list']) || empty($assoc['list'])) {
  138. continue;
  139. }
  140. $generateKeys = static function ($id) use ($assocMetadata): EntityCacheKey {
  141. return new EntityCacheKey($assocMetadata->rootEntityName, $id);
  142. };
  143. $collection = new PersistentCollection($this->em, $assocMetadata, new ArrayCollection());
  144. $assocKeys = new CollectionCacheEntry(array_map($generateKeys, $assoc['list']));
  145. $assocEntries = $assocRegion->getMultiple($assocKeys);
  146. foreach ($assoc['list'] as $assocIndex => $assocId) {
  147. $assocEntry = is_array($assocEntries) && array_key_exists($assocIndex, $assocEntries) ? $assocEntries[$assocIndex] : null;
  148. if ($assocEntry === null) {
  149. if ($this->cacheLogger !== null) {
  150. $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKeys->identifiers[$assocIndex]);
  151. }
  152. $this->uow->hydrationComplete();
  153. return null;
  154. }
  155. $element = $this->uow->createEntity($assocEntry->class, $assocEntry->resolveAssociationEntries($this->em), self::$hints);
  156. $collection->hydrateSet($assocIndex, $element);
  157. if ($this->cacheLogger !== null) {
  158. $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKeys->identifiers[$assocIndex]);
  159. }
  160. }
  161. $data[$name] = $collection;
  162. $collection->setInitialized(true);
  163. }
  164. foreach ($data as $fieldName => $unCachedAssociationData) {
  165. // In some scenarios, such as EAGER+ASSOCIATION+ID+CACHE, the
  166. // cache key information in `$cacheEntry` will not contain details
  167. // for fields that are associations.
  168. //
  169. // This means that `$data` keys for some associations that may
  170. // actually not be cached will not be converted to actual association
  171. // data, yet they contain L2 cache AssociationCacheEntry objects.
  172. //
  173. // We need to unwrap those associations into proxy references,
  174. // since we don't have actual data for them except for identifiers.
  175. if ($unCachedAssociationData instanceof AssociationCacheEntry) {
  176. $data[$fieldName] = $this->em->getReference(
  177. $unCachedAssociationData->class,
  178. $unCachedAssociationData->identifier
  179. );
  180. }
  181. }
  182. $result[$index] = $this->uow->createEntity($entityEntry->class, $data, self::$hints);
  183. }
  184. $this->uow->hydrationComplete();
  185. return $result;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = [])
  191. {
  192. if ($rsm->scalarMappings) {
  193. throw new CacheException('Second level cache does not support scalar results.');
  194. }
  195. if (count($rsm->entityMappings) > 1) {
  196. throw new CacheException('Second level cache does not support multiple root entities.');
  197. }
  198. if (! $rsm->isSelect) {
  199. throw new CacheException('Second-level cache query supports only select statements.');
  200. }
  201. if (($hints[Query\SqlWalker::HINT_PARTIAL] ?? false) === true || ($hints[Query::HINT_FORCE_PARTIAL_LOAD] ?? false) === true) {
  202. throw new CacheException('Second level cache does not support partial entities.');
  203. }
  204. if (! ($key->cacheMode & Cache::MODE_PUT)) {
  205. return false;
  206. }
  207. $data = [];
  208. $entityName = reset($rsm->aliasMap);
  209. $rootAlias = key($rsm->aliasMap);
  210. $persister = $this->uow->getEntityPersister($entityName);
  211. if (! $persister instanceof CachedEntityPersister) {
  212. throw CacheException::nonCacheableEntity($entityName);
  213. }
  214. $region = $persister->getCacheRegion();
  215. $cm = $this->em->getClassMetadata($entityName);
  216. assert($cm instanceof ClassMetadata);
  217. foreach ($result as $index => $entity) {
  218. $identifier = $this->uow->getEntityIdentifier($entity);
  219. $entityKey = new EntityCacheKey($cm->rootEntityName, $identifier);
  220. if (($key->cacheMode & Cache::MODE_REFRESH) || ! $region->contains($entityKey)) {
  221. // Cancel put result if entity put fail
  222. if (! $persister->storeEntityCache($entity, $entityKey)) {
  223. return false;
  224. }
  225. }
  226. $data[$index]['identifier'] = $identifier;
  227. $data[$index]['associations'] = [];
  228. // @TODO - move to cache hydration components
  229. foreach ($rsm->relationMap as $alias => $name) {
  230. $parentAlias = $rsm->parentAliasMap[$alias];
  231. $parentClass = $rsm->aliasMap[$parentAlias];
  232. $metadata = $this->em->getClassMetadata($parentClass);
  233. $assoc = $metadata->associationMappings[$name];
  234. $assocValue = $this->getAssociationValue($rsm, $alias, $entity);
  235. if ($assocValue === null) {
  236. continue;
  237. }
  238. // root entity association
  239. if ($rootAlias === $parentAlias) {
  240. // Cancel put result if association put fail
  241. $assocInfo = $this->storeAssociationCache($key, $assoc, $assocValue);
  242. if ($assocInfo === null) {
  243. return false;
  244. }
  245. $data[$index]['associations'][$name] = $assocInfo;
  246. continue;
  247. }
  248. // store single nested association
  249. if (! is_array($assocValue)) {
  250. // Cancel put result if association put fail
  251. if ($this->storeAssociationCache($key, $assoc, $assocValue) === null) {
  252. return false;
  253. }
  254. continue;
  255. }
  256. // store array of nested association
  257. foreach ($assocValue as $aVal) {
  258. // Cancel put result if association put fail
  259. if ($this->storeAssociationCache($key, $assoc, $aVal) === null) {
  260. return false;
  261. }
  262. }
  263. }
  264. }
  265. return $this->region->put($key, new QueryCacheEntry($data));
  266. }
  267. /**
  268. * @param array<string,mixed> $assoc
  269. * @param mixed $assocValue
  270. *
  271. * @return mixed[]|null
  272. *
  273. * @psalm-return array{targetEntity: string, type: mixed, list?: array[], identifier?: array}|null
  274. */
  275. private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocValue)
  276. {
  277. $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']);
  278. $assocMetadata = $assocPersister->getClassMetadata();
  279. $assocRegion = $assocPersister->getCacheRegion();
  280. // Handle *-to-one associations
  281. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  282. $assocIdentifier = $this->uow->getEntityIdentifier($assocValue);
  283. $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier);
  284. if (! $assocValue instanceof Proxy && ($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) {
  285. // Entity put fail
  286. if (! $assocPersister->storeEntityCache($assocValue, $entityKey)) {
  287. return null;
  288. }
  289. }
  290. return [
  291. 'targetEntity' => $assocMetadata->rootEntityName,
  292. 'identifier' => $assocIdentifier,
  293. 'type' => $assoc['type'],
  294. ];
  295. }
  296. // Handle *-to-many associations
  297. $list = [];
  298. foreach ($assocValue as $assocItemIndex => $assocItem) {
  299. $assocIdentifier = $this->uow->getEntityIdentifier($assocItem);
  300. $entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier);
  301. if (($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) {
  302. // Entity put fail
  303. if (! $assocPersister->storeEntityCache($assocItem, $entityKey)) {
  304. return null;
  305. }
  306. }
  307. $list[$assocItemIndex] = $assocIdentifier;
  308. }
  309. return [
  310. 'targetEntity' => $assocMetadata->rootEntityName,
  311. 'type' => $assoc['type'],
  312. 'list' => $list,
  313. ];
  314. }
  315. /**
  316. * @param string $assocAlias
  317. * @param object $entity
  318. *
  319. * @return array<object>|object
  320. */
  321. private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity)
  322. {
  323. $path = [];
  324. $alias = $assocAlias;
  325. while (isset($rsm->parentAliasMap[$alias])) {
  326. $parent = $rsm->parentAliasMap[$alias];
  327. $field = $rsm->relationMap[$alias];
  328. $class = $rsm->aliasMap[$parent];
  329. array_unshift($path, [
  330. 'field' => $field,
  331. 'class' => $class,
  332. ]);
  333. $alias = $parent;
  334. }
  335. return $this->getAssociationPathValue($entity, $path);
  336. }
  337. /**
  338. * @param mixed $value
  339. * @param array<mixed> $path
  340. *
  341. * @return mixed
  342. */
  343. private function getAssociationPathValue($value, array $path)
  344. {
  345. $mapping = array_shift($path);
  346. $metadata = $this->em->getClassMetadata($mapping['class']);
  347. $assoc = $metadata->associationMappings[$mapping['field']];
  348. $value = $metadata->getFieldValue($value, $mapping['field']);
  349. if ($value === null) {
  350. return null;
  351. }
  352. if (empty($path)) {
  353. return $value;
  354. }
  355. // Handle *-to-one associations
  356. if ($assoc['type'] & ClassMetadata::TO_ONE) {
  357. return $this->getAssociationPathValue($value, $path);
  358. }
  359. $values = [];
  360. foreach ($value as $item) {
  361. $values[] = $this->getAssociationPathValue($item, $path);
  362. }
  363. return $values;
  364. }
  365. /**
  366. * {@inheritdoc}
  367. */
  368. public function clear()
  369. {
  370. return $this->region->evictAll();
  371. }
  372. /**
  373. * {@inheritdoc}
  374. */
  375. public function getRegion()
  376. {
  377. return $this->region;
  378. }
  379. }