AbstractQuery.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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;
  20. use Doctrine\Common\Util\ClassUtils;
  21. use Doctrine\Common\Collections\ArrayCollection;
  22. use Doctrine\DBAL\Types\Type;
  23. use Doctrine\DBAL\Cache\QueryCacheProfile;
  24. use Doctrine\ORM\Query\QueryException;
  25. use Doctrine\ORM\ORMInvalidArgumentException;
  26. /**
  27. * Base contract for ORM queries. Base class for Query and NativeQuery.
  28. *
  29. * @link www.doctrine-project.org
  30. * @since 2.0
  31. * @author Benjamin Eberlei <kontakt@beberlei.de>
  32. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  33. * @author Jonathan Wage <jonwage@gmail.com>
  34. * @author Roman Borschel <roman@code-factory.org>
  35. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  36. */
  37. abstract class AbstractQuery
  38. {
  39. /* Hydration mode constants */
  40. /**
  41. * Hydrates an object graph. This is the default behavior.
  42. */
  43. const HYDRATE_OBJECT = 1;
  44. /**
  45. * Hydrates an array graph.
  46. */
  47. const HYDRATE_ARRAY = 2;
  48. /**
  49. * Hydrates a flat, rectangular result set with scalar values.
  50. */
  51. const HYDRATE_SCALAR = 3;
  52. /**
  53. * Hydrates a single scalar value.
  54. */
  55. const HYDRATE_SINGLE_SCALAR = 4;
  56. /**
  57. * Very simple object hydrator (optimized for performance).
  58. */
  59. const HYDRATE_SIMPLEOBJECT = 5;
  60. /**
  61. * The parameter map of this query.
  62. *
  63. * @var \Doctrine\Common\Collections\ArrayCollection
  64. */
  65. protected $parameters;
  66. /**
  67. * The user-specified ResultSetMapping to use.
  68. *
  69. * @var \Doctrine\ORM\Query\ResultSetMapping
  70. */
  71. protected $_resultSetMapping;
  72. /**
  73. * The entity manager used by this query object.
  74. *
  75. * @var \Doctrine\ORM\EntityManager
  76. */
  77. protected $_em;
  78. /**
  79. * The map of query hints.
  80. *
  81. * @var array
  82. */
  83. protected $_hints = array();
  84. /**
  85. * The hydration mode.
  86. *
  87. * @var integer
  88. */
  89. protected $_hydrationMode = self::HYDRATE_OBJECT;
  90. /**
  91. * @param \Doctrine\DBAL\Cache\QueryCacheProfile
  92. */
  93. protected $_queryCacheProfile;
  94. /**
  95. * Whether or not expire the result cache.
  96. *
  97. * @var boolean
  98. */
  99. protected $_expireResultCache = false;
  100. /**
  101. * @param \Doctrine\DBAL\Cache\QueryCacheProfile
  102. */
  103. protected $_hydrationCacheProfile;
  104. /**
  105. * Initializes a new instance of a class derived from <tt>AbstractQuery</tt>.
  106. *
  107. * @param \Doctrine\ORM\EntityManager $em
  108. */
  109. public function __construct(EntityManager $em)
  110. {
  111. $this->_em = $em;
  112. $this->parameters = new ArrayCollection();
  113. }
  114. /**
  115. * Gets the SQL query that corresponds to this query object.
  116. * The returned SQL syntax depends on the connection driver that is used
  117. * by this query object at the time of this method call.
  118. *
  119. * @return string SQL query
  120. */
  121. abstract public function getSQL();
  122. /**
  123. * Retrieves the associated EntityManager of this Query instance.
  124. *
  125. * @return \Doctrine\ORM\EntityManager
  126. */
  127. public function getEntityManager()
  128. {
  129. return $this->_em;
  130. }
  131. /**
  132. * Frees the resources used by the query object.
  133. *
  134. * Resets Parameters, Parameter Types and Query Hints.
  135. *
  136. * @return void
  137. */
  138. public function free()
  139. {
  140. $this->parameters = new ArrayCollection();
  141. $this->_hints = array();
  142. }
  143. /**
  144. * Get all defined parameters.
  145. *
  146. * @return \Doctrine\Common\Collections\ArrayCollection The defined query parameters.
  147. */
  148. public function getParameters()
  149. {
  150. return $this->parameters;
  151. }
  152. /**
  153. * Gets a query parameter.
  154. *
  155. * @param mixed $key The key (index or name) of the bound parameter.
  156. *
  157. * @return mixed The value of the bound parameter.
  158. */
  159. public function getParameter($key)
  160. {
  161. $filteredParameters = $this->parameters->filter(
  162. function ($parameter) use ($key)
  163. {
  164. // Must not be identical because of string to integer conversion
  165. return ($key == $parameter->getName());
  166. }
  167. );
  168. return count($filteredParameters) ? $filteredParameters->first() : null;
  169. }
  170. /**
  171. * Sets a collection of query parameters.
  172. *
  173. * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters
  174. *
  175. * @return \Doctrine\ORM\AbstractQuery This query instance.
  176. */
  177. public function setParameters($parameters)
  178. {
  179. // BC compatibility with 2.3-
  180. if (is_array($parameters)) {
  181. $parameterCollection = new ArrayCollection();
  182. foreach ($parameters as $key => $value) {
  183. $parameter = new Query\Parameter($key, $value);
  184. $parameterCollection->add($parameter);
  185. }
  186. $parameters = $parameterCollection;
  187. }
  188. $this->parameters = $parameters;
  189. return $this;
  190. }
  191. /**
  192. * Sets a query parameter.
  193. *
  194. * @param string|int $key The parameter position or name.
  195. * @param mixed $value The parameter value.
  196. * @param string|null $type The parameter type. If specified, the given value will be run through
  197. * the type conversion of this type. This is usually not needed for
  198. * strings and numeric types.
  199. *
  200. * @return \Doctrine\ORM\AbstractQuery This query instance.
  201. */
  202. public function setParameter($key, $value, $type = null)
  203. {
  204. $filteredParameters = $this->parameters->filter(
  205. function ($parameter) use ($key)
  206. {
  207. // Must not be identical because of string to integer conversion
  208. return ($key == $parameter->getName());
  209. }
  210. );
  211. if (count($filteredParameters)) {
  212. $parameter = $filteredParameters->first();
  213. $parameter->setValue($value, $type);
  214. return $this;
  215. }
  216. $parameter = new Query\Parameter($key, $value, $type);
  217. $this->parameters->add($parameter);
  218. return $this;
  219. }
  220. /**
  221. * Processes an individual parameter value.
  222. *
  223. * @param mixed $value
  224. *
  225. * @return array
  226. *
  227. * @throws ORMInvalidArgumentException
  228. */
  229. public function processParameterValue($value)
  230. {
  231. if (is_array($value)) {
  232. foreach ($value as $key => $paramValue) {
  233. $paramValue = $this->processParameterValue($paramValue);
  234. $value[$key] = is_array($paramValue) ? reset($paramValue) : $paramValue;
  235. }
  236. return $value;
  237. }
  238. if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) {
  239. $value = $this->_em->getUnitOfWork()->getSingleIdentifierValue($value);
  240. if ($value === null) {
  241. throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
  242. }
  243. }
  244. if ($value instanceof Mapping\ClassMetadata) {
  245. return $value->name;
  246. }
  247. return $value;
  248. }
  249. /**
  250. * Sets the ResultSetMapping that should be used for hydration.
  251. *
  252. * @param \Doctrine\ORM\Query\ResultSetMapping $rsm
  253. *
  254. * @return \Doctrine\ORM\AbstractQuery
  255. */
  256. public function setResultSetMapping(Query\ResultSetMapping $rsm)
  257. {
  258. $this->translateNamespaces($rsm);
  259. $this->_resultSetMapping = $rsm;
  260. return $this;
  261. }
  262. /**
  263. * Allows to translate entity namespaces to full qualified names.
  264. *
  265. * @param Query\ResultSetMapping $rsm
  266. *
  267. * @return void
  268. */
  269. private function translateNamespaces(Query\ResultSetMapping $rsm)
  270. {
  271. $entityManager = $this->_em;
  272. $translate = function ($alias) use ($entityManager) {
  273. return $entityManager->getClassMetadata($alias)->getName();
  274. };
  275. $rsm->aliasMap = array_map($translate, $rsm->aliasMap);
  276. $rsm->declaringClasses = array_map($translate, $rsm->declaringClasses);
  277. }
  278. /**
  279. * Set a cache profile for hydration caching.
  280. *
  281. * If no result cache driver is set in the QueryCacheProfile, the default
  282. * result cache driver is used from the configuration.
  283. *
  284. * Important: Hydration caching does NOT register entities in the
  285. * UnitOfWork when retrieved from the cache. Never use result cached
  286. * entities for requests that also flush the EntityManager. If you want
  287. * some form of caching with UnitOfWork registration you should use
  288. * {@see AbstractQuery::setResultCacheProfile()}.
  289. *
  290. * @example
  291. * $lifetime = 100;
  292. * $resultKey = "abc";
  293. * $query->setHydrationCacheProfile(new QueryCacheProfile());
  294. * $query->setHydrationCacheProfile(new QueryCacheProfile($lifetime, $resultKey));
  295. *
  296. * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
  297. *
  298. * @return \Doctrine\ORM\AbstractQuery
  299. */
  300. public function setHydrationCacheProfile(QueryCacheProfile $profile = null)
  301. {
  302. if ( ! $profile->getResultCacheDriver()) {
  303. $resultCacheDriver = $this->_em->getConfiguration()->getHydrationCacheImpl();
  304. $profile = $profile->setResultCacheDriver($resultCacheDriver);
  305. }
  306. $this->_hydrationCacheProfile = $profile;
  307. return $this;
  308. }
  309. /**
  310. * @return \Doctrine\DBAL\Cache\QueryCacheProfile
  311. */
  312. public function getHydrationCacheProfile()
  313. {
  314. return $this->_hydrationCacheProfile;
  315. }
  316. /**
  317. * Set a cache profile for the result cache.
  318. *
  319. * If no result cache driver is set in the QueryCacheProfile, the default
  320. * result cache driver is used from the configuration.
  321. *
  322. * @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
  323. *
  324. * @return \Doctrine\ORM\AbstractQuery
  325. */
  326. public function setResultCacheProfile(QueryCacheProfile $profile = null)
  327. {
  328. if ( ! $profile->getResultCacheDriver()) {
  329. $resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl();
  330. $profile = $profile->setResultCacheDriver($resultCacheDriver);
  331. }
  332. $this->_queryCacheProfile = $profile;
  333. return $this;
  334. }
  335. /**
  336. * Defines a cache driver to be used for caching result sets and implicitly enables caching.
  337. *
  338. * @param \Doctrine\Common\Cache\Cache|null $resultCacheDriver Cache driver
  339. *
  340. * @return \Doctrine\ORM\AbstractQuery
  341. *
  342. * @throws ORMException
  343. */
  344. public function setResultCacheDriver($resultCacheDriver = null)
  345. {
  346. if ($resultCacheDriver !== null && ! ($resultCacheDriver instanceof \Doctrine\Common\Cache\Cache)) {
  347. throw ORMException::invalidResultCacheDriver();
  348. }
  349. $this->_queryCacheProfile = $this->_queryCacheProfile
  350. ? $this->_queryCacheProfile->setResultCacheDriver($resultCacheDriver)
  351. : new QueryCacheProfile(0, null, $resultCacheDriver);
  352. return $this;
  353. }
  354. /**
  355. * Returns the cache driver used for caching result sets.
  356. *
  357. * @deprecated
  358. *
  359. * @return \Doctrine\Common\Cache\Cache Cache driver
  360. */
  361. public function getResultCacheDriver()
  362. {
  363. if ($this->_queryCacheProfile && $this->_queryCacheProfile->getResultCacheDriver()) {
  364. return $this->_queryCacheProfile->getResultCacheDriver();
  365. }
  366. return $this->_em->getConfiguration()->getResultCacheImpl();
  367. }
  368. /**
  369. * Set whether or not to cache the results of this query and if so, for
  370. * how long and which ID to use for the cache entry.
  371. *
  372. * @param boolean $bool
  373. * @param integer $lifetime
  374. * @param string $resultCacheId
  375. *
  376. * @return \Doctrine\ORM\AbstractQuery This query instance.
  377. */
  378. public function useResultCache($bool, $lifetime = null, $resultCacheId = null)
  379. {
  380. if ($bool) {
  381. $this->setResultCacheLifetime($lifetime);
  382. $this->setResultCacheId($resultCacheId);
  383. return $this;
  384. }
  385. $this->_queryCacheProfile = null;
  386. return $this;
  387. }
  388. /**
  389. * Defines how long the result cache will be active before expire.
  390. *
  391. * @param integer $lifetime How long the cache entry is valid.
  392. *
  393. * @return \Doctrine\ORM\AbstractQuery This query instance.
  394. */
  395. public function setResultCacheLifetime($lifetime)
  396. {
  397. $lifetime = ($lifetime !== null) ? (int) $lifetime : 0;
  398. $this->_queryCacheProfile = $this->_queryCacheProfile
  399. ? $this->_queryCacheProfile->setLifetime($lifetime)
  400. : new QueryCacheProfile($lifetime, null, $this->_em->getConfiguration()->getResultCacheImpl());
  401. return $this;
  402. }
  403. /**
  404. * Retrieves the lifetime of resultset cache.
  405. *
  406. * @deprecated
  407. *
  408. * @return integer
  409. */
  410. public function getResultCacheLifetime()
  411. {
  412. return $this->_queryCacheProfile ? $this->_queryCacheProfile->getLifetime() : 0;
  413. }
  414. /**
  415. * Defines if the result cache is active or not.
  416. *
  417. * @param boolean $expire Whether or not to force resultset cache expiration.
  418. *
  419. * @return \Doctrine\ORM\AbstractQuery This query instance.
  420. */
  421. public function expireResultCache($expire = true)
  422. {
  423. $this->_expireResultCache = $expire;
  424. return $this;
  425. }
  426. /**
  427. * Retrieves if the resultset cache is active or not.
  428. *
  429. * @return boolean
  430. */
  431. public function getExpireResultCache()
  432. {
  433. return $this->_expireResultCache;
  434. }
  435. /**
  436. * @return QueryCacheProfile
  437. */
  438. public function getQueryCacheProfile()
  439. {
  440. return $this->_queryCacheProfile;
  441. }
  442. /**
  443. * Change the default fetch mode of an association for this query.
  444. *
  445. * $fetchMode can be one of ClassMetadata::FETCH_EAGER or ClassMetadata::FETCH_LAZY
  446. *
  447. * @param string $class
  448. * @param string $assocName
  449. * @param int $fetchMode
  450. *
  451. * @return AbstractQuery
  452. */
  453. public function setFetchMode($class, $assocName, $fetchMode)
  454. {
  455. if ($fetchMode !== Mapping\ClassMetadata::FETCH_EAGER) {
  456. $fetchMode = Mapping\ClassMetadata::FETCH_LAZY;
  457. }
  458. $this->_hints['fetchMode'][$class][$assocName] = $fetchMode;
  459. return $this;
  460. }
  461. /**
  462. * Defines the processing mode to be used during hydration / result set transformation.
  463. *
  464. * @param integer $hydrationMode Doctrine processing mode to be used during hydration process.
  465. * One of the Query::HYDRATE_* constants.
  466. *
  467. * @return \Doctrine\ORM\AbstractQuery This query instance.
  468. */
  469. public function setHydrationMode($hydrationMode)
  470. {
  471. $this->_hydrationMode = $hydrationMode;
  472. return $this;
  473. }
  474. /**
  475. * Gets the hydration mode currently used by the query.
  476. *
  477. * @return integer
  478. */
  479. public function getHydrationMode()
  480. {
  481. return $this->_hydrationMode;
  482. }
  483. /**
  484. * Gets the list of results for the query.
  485. *
  486. * Alias for execute(null, $hydrationMode = HYDRATE_OBJECT).
  487. *
  488. * @param int $hydrationMode
  489. *
  490. * @return array
  491. */
  492. public function getResult($hydrationMode = self::HYDRATE_OBJECT)
  493. {
  494. return $this->execute(null, $hydrationMode);
  495. }
  496. /**
  497. * Gets the array of results for the query.
  498. *
  499. * Alias for execute(null, HYDRATE_ARRAY).
  500. *
  501. * @return array
  502. */
  503. public function getArrayResult()
  504. {
  505. return $this->execute(null, self::HYDRATE_ARRAY);
  506. }
  507. /**
  508. * Gets the scalar results for the query.
  509. *
  510. * Alias for execute(null, HYDRATE_SCALAR).
  511. *
  512. * @return array
  513. */
  514. public function getScalarResult()
  515. {
  516. return $this->execute(null, self::HYDRATE_SCALAR);
  517. }
  518. /**
  519. * Get exactly one result or null.
  520. *
  521. * @param int $hydrationMode
  522. *
  523. * @return mixed
  524. *
  525. * @throws NonUniqueResultException
  526. */
  527. public function getOneOrNullResult($hydrationMode = null)
  528. {
  529. $result = $this->execute(null, $hydrationMode);
  530. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  531. return null;
  532. }
  533. if ( ! is_array($result)) {
  534. return $result;
  535. }
  536. if (count($result) > 1) {
  537. throw new NonUniqueResultException;
  538. }
  539. return array_shift($result);
  540. }
  541. /**
  542. * Gets the single result of the query.
  543. *
  544. * Enforces the presence as well as the uniqueness of the result.
  545. *
  546. * If the result is not unique, a NonUniqueResultException is thrown.
  547. * If there is no result, a NoResultException is thrown.
  548. *
  549. * @param integer $hydrationMode
  550. *
  551. * @return mixed
  552. *
  553. * @throws NonUniqueResultException If the query result is not unique.
  554. * @throws NoResultException If the query returned no result.
  555. */
  556. public function getSingleResult($hydrationMode = null)
  557. {
  558. $result = $this->execute(null, $hydrationMode);
  559. if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
  560. throw new NoResultException;
  561. }
  562. if ( ! is_array($result)) {
  563. return $result;
  564. }
  565. if (count($result) > 1) {
  566. throw new NonUniqueResultException;
  567. }
  568. return array_shift($result);
  569. }
  570. /**
  571. * Gets the single scalar result of the query.
  572. *
  573. * Alias for getSingleResult(HYDRATE_SINGLE_SCALAR).
  574. *
  575. * @return mixed
  576. *
  577. * @throws QueryException If the query result is not unique.
  578. */
  579. public function getSingleScalarResult()
  580. {
  581. return $this->getSingleResult(self::HYDRATE_SINGLE_SCALAR);
  582. }
  583. /**
  584. * Sets a query hint. If the hint name is not recognized, it is silently ignored.
  585. *
  586. * @param string $name The name of the hint.
  587. * @param mixed $value The value of the hint.
  588. *
  589. * @return \Doctrine\ORM\AbstractQuery
  590. */
  591. public function setHint($name, $value)
  592. {
  593. $this->_hints[$name] = $value;
  594. return $this;
  595. }
  596. /**
  597. * Gets the value of a query hint. If the hint name is not recognized, FALSE is returned.
  598. *
  599. * @param string $name The name of the hint.
  600. *
  601. * @return mixed The value of the hint or FALSE, if the hint name is not recognized.
  602. */
  603. public function getHint($name)
  604. {
  605. return isset($this->_hints[$name]) ? $this->_hints[$name] : false;
  606. }
  607. /**
  608. * Check if the query has a hint
  609. *
  610. * @param string $name The name of the hint
  611. *
  612. * @return bool False if the query does not have any hint
  613. */
  614. public function hasHint($name)
  615. {
  616. return isset($this->_hints[$name]);
  617. }
  618. /**
  619. * Return the key value map of query hints that are currently set.
  620. *
  621. * @return array
  622. */
  623. public function getHints()
  624. {
  625. return $this->_hints;
  626. }
  627. /**
  628. * Executes the query and returns an IterableResult that can be used to incrementally
  629. * iterate over the result.
  630. *
  631. * @param ArrayCollection|array|null $parameters The query parameters.
  632. * @param integer|null $hydrationMode The hydration mode to use.
  633. *
  634. * @return \Doctrine\ORM\Internal\Hydration\IterableResult
  635. */
  636. public function iterate($parameters = null, $hydrationMode = null)
  637. {
  638. if ($hydrationMode !== null) {
  639. $this->setHydrationMode($hydrationMode);
  640. }
  641. if ( ! empty($parameters)) {
  642. $this->setParameters($parameters);
  643. }
  644. $stmt = $this->_doExecute();
  645. return $this->_em->newHydrator($this->_hydrationMode)->iterate(
  646. $stmt, $this->_resultSetMapping, $this->_hints
  647. );
  648. }
  649. /**
  650. * Executes the query.
  651. *
  652. * @param ArrayCollection|array|null $parameters Query parameters.
  653. * @param integer|null $hydrationMode Processing mode to be used during the hydration process.
  654. *
  655. * @return mixed
  656. */
  657. public function execute($parameters = null, $hydrationMode = null)
  658. {
  659. if ($hydrationMode !== null) {
  660. $this->setHydrationMode($hydrationMode);
  661. }
  662. if ( ! empty($parameters)) {
  663. $this->setParameters($parameters);
  664. }
  665. $setCacheEntry = function() {};
  666. if ($this->_hydrationCacheProfile !== null) {
  667. list($cacheKey, $realCacheKey) = $this->getHydrationCacheId();
  668. $queryCacheProfile = $this->getHydrationCacheProfile();
  669. $cache = $queryCacheProfile->getResultCacheDriver();
  670. $result = $cache->fetch($cacheKey);
  671. if (isset($result[$realCacheKey])) {
  672. return $result[$realCacheKey];
  673. }
  674. if ( ! $result) {
  675. $result = array();
  676. }
  677. $setCacheEntry = function($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile) {
  678. $result[$realCacheKey] = $data;
  679. $cache->save($cacheKey, $result, $queryCacheProfile->getLifetime());
  680. };
  681. }
  682. $stmt = $this->_doExecute();
  683. if (is_numeric($stmt)) {
  684. $setCacheEntry($stmt);
  685. return $stmt;
  686. }
  687. $data = $this->_em->newHydrator($this->_hydrationMode)->hydrateAll(
  688. $stmt, $this->_resultSetMapping, $this->_hints
  689. );
  690. $setCacheEntry($data);
  691. return $data;
  692. }
  693. /**
  694. * Get the result cache id to use to store the result set cache entry.
  695. * Will return the configured id if it exists otherwise a hash will be
  696. * automatically generated for you.
  697. *
  698. * @return array ($key, $hash)
  699. */
  700. protected function getHydrationCacheId()
  701. {
  702. $parameters = array();
  703. foreach ($this->getParameters() as $parameter) {
  704. $parameters[$parameter->getName()] = $this->processParameterValue($parameter->getValue());
  705. }
  706. $sql = $this->getSQL();
  707. $queryCacheProfile = $this->getHydrationCacheProfile();
  708. $hints = $this->getHints();
  709. $hints['hydrationMode'] = $this->getHydrationMode();
  710. ksort($hints);
  711. return $queryCacheProfile->generateCacheKeys($sql, $parameters, $hints);
  712. }
  713. /**
  714. * Set the result cache id to use to store the result set cache entry.
  715. * If this is not explicitly set by the developer then a hash is automatically
  716. * generated for you.
  717. *
  718. * @param string $id
  719. *
  720. * @return \Doctrine\ORM\AbstractQuery This query instance.
  721. */
  722. public function setResultCacheId($id)
  723. {
  724. $this->_queryCacheProfile = $this->_queryCacheProfile
  725. ? $this->_queryCacheProfile->setCacheKey($id)
  726. : new QueryCacheProfile(0, $id, $this->_em->getConfiguration()->getResultCacheImpl());
  727. return $this;
  728. }
  729. /**
  730. * Get the result cache id to use to store the result set cache entry if set.
  731. *
  732. * @deprecated
  733. *
  734. * @return string
  735. */
  736. public function getResultCacheId()
  737. {
  738. return $this->_queryCacheProfile ? $this->_queryCacheProfile->getCacheKey() : null;
  739. }
  740. /**
  741. * Executes the query and returns a the resulting Statement object.
  742. *
  743. * @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results.
  744. */
  745. abstract protected function _doExecute();
  746. /**
  747. * Cleanup Query resource when clone is called.
  748. *
  749. * @return void
  750. */
  751. public function __clone()
  752. {
  753. $this->parameters = new ArrayCollection();
  754. $this->_hints = array();
  755. }
  756. }